多模块项目中的 Maven 测试依赖

我使用 maven 来构建一个多模块项目。我的模块2在编译范围内依赖于模块1 src,在测试范围内依赖于模块1测试。

单元2 -

   <dependency>
<groupId>blah</groupId>
<artifactId>MODULE1</artifactId>
<version>blah</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>

假设我的模块3在编译时依赖于 Module1src 和测试。

单元3 -

   <dependency>
<groupId>blah</groupId>
<artifactId>MODULE1</artifactId>
<version>blah</version>
<classifier>tests</classifier>
<scope>compile</scope>
</dependency>

当我运行 mvn clean install时,我的构建一直运行到模块3,在模块3失败,因为它不能解决模块1的测试依赖性。然后我单独在模块3上做一个 mvn install,返回并在我的父 pom 上运行 mvn install使其构建。我该怎么补救?

64249 次浏览

I have a doubt about what you are trying to do but but I'll assume you want to reuse the tests that you have created for a project (module1) in another. As explained in the note at the bottom of the Guide to using attached tests:

Note that previous editions of this guide suggested to use <classifier>tests</classifier> instead of <type>test-jar</type>. While this currently works for some cases, it does not properly work during a reactor build of the test JAR module and any consumer if a lifecycle phase prior to install is invoked. In such a scenario, Maven will not resolve the test JAR from the output of the reactor build but from the local/remote repository. Apparently, the JAR from the repositories could be outdated or completely missing, causing a build failure (cf. MNG-2045).

So, first, to package up compiled tests in a JAR and deploy them for general reuse, configure the maven-jar-plugin as follows:

<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>

Then, install/deploy the test JAR artifact as usual (using mvn install or mvn deploy).

Finally, to use the test JAR, you should specify a dependency with a specified type of test-jar:

<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>

Regarding to my comment to Pascals question i think i have found a stuitable answer :

<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
<phase>test-compile</phase>
</execution>
</executions>
<configuration>
<outputDirectory>${basedir}\target</outputDirectory>
</configuration>
</plugin>
</plugins>

The main difference here as you see here is the <phase> tag.

I will create the test-jar and it will be available in the compile phase of the tests and not only after the package phase.

Works for me.