在Maven中共享测试代码

如何依赖Maven中另一个模块的测试代码?

例如,我有2个模块:

  • 基地
  • 主要的

我想在主要的测试案例,以扩展基本测试类的基础。这可能吗?

更新:发现了一个可接受的答案,它涉及到创建一个测试JAR.

68408 次浏览

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>

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>

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. See also "How to create a jar containing test classes".

This creates jar file of code from src/test/java using the jar plugin so that modules with tests can share code.

<project>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</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>
<type>test-jar</type>
<scope>test</scope>
</dependency>
</dependencies>
...
</project>

I recommend using type instead of classifier (see also: classifier). It 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>

Worked for me for 1 project, but I didn't for another after doing exactly the same steps.

So I debugged:

  1. After mvn clean install I checked /target directory: .jar was there so thats good
  2. Ran mvn dependency:tree on a project which should use those test classes. Noticed that generated jar file with test classes is marked as dependency, so thats good.
  3. Conclusion could be only one - I restarted my Intellj. At first class import was still not visible, but after a minute it started to see it!

Note: I only restarted Intellj, no caches removal etc