views:

1403

answers:

4

How can you depend on test code from another module in Maven?

Example, I have 2 modules:

  • Base
  • Main

I would like a test case in Main to extend a base test class in Base. Is this possible?

Update: Found an acceptable answer, which involves creating a test jar.

A: 

Yep ... just include the Base module as a dependency in Main. If you're only inheriting test code, then you can use the scope tag to make sure Maven doesn't include the code in your artifact when deployed. Something like this should work:

<dependency>
    <groupId>BaseGroup</groupId>
    <artifactId>Base</artifactId>
    <version>0.1.0-SNAPSHOT</version>
    <scope>test</scope>
</dependency>
Steve Moyer
I don't think that's quite enough though...
rogerdpack
+3  A: 

We solved this by making a maven project with test code as the src/main/java and adding the following dependency to projects:

 <dependency>
  <groupId>foo</groupId>
  <artifactId>test-base</artifactId>
  <version>1</version>
  <scope>test</scope>
 </dependency>
sal
Yep, that'd work, thanks! See my comment below for alternate answer that I prefer.
flicken
+6  A: 

Thanks for the base module suggestion. However, I'd rather not create a new module for just this purpose.

Found an acceptable answer in the Surefire Maven documentation and a blog:

This creates jar file of code from src/test/java so modules with tests can share code:

<project>
  <build>
    <plugins>
     <plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-jar-plugin</artifactId>
       <version>2.2</version>
       <executions>
         <execution>
           <goals>
             <goal>test-jar</goal>
           </goals>
         </execution>
       </executions>
     </plugin>
    </plugins>
  </build>
</project>

In order to use the attached test JAR that was created above you simply specify a dependency on the main artifact with a specified classifier of tests:

<project>
  ...
  <dependencies>
    <dependency>
      <groupId>com.myco.app</groupId>
      <artifactId>foo</artifactId>
      <version>1.0-SNAPSHOT</version>
      <classifier>tests</classifier>
      <scope>test</scope>
    </dependency>
  </dependencies>
  ...
</project>
flicken
Note, that there can be issues with using <classifier>tests</classifier in the dependency. Instead, use <type>test-jar</type>. Here's one issue in Maven http://jira.codehaus.org/browse/MNG-2045 and an unrelated one in IntelliJ http://youtrack.jetbrains.net/issue/IDEA-54254
Emil
+6  A: 

I recommend using type instead of classifier. Tt tells Maven a bit more explicitly what you are doing (and I've found that m2eclipse and q4e both like it better).

<dependency>
  <groupId>com.myco.app</groupId>
  <artifactId>foo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <type>test-jar</type>
  <scope>test</scope>
</dependency>
Ben