在Maven中共享testing代码

你如何依靠Maven中另一个模块的testing代码?

例如,我有2个模块:

  • 基础
  • 主要

我想在Main中的一个testing用例扩展Base中的基础testing类。 这可能吗?

更新:find了一个可以接受的答案 ,这涉及到创build一个testingjar。

我build议使用types而不是分类器 (另见: 分类器 )。 它更清楚地告诉Maven你在做什么(我发现m2eclipse和q4e都更喜欢它)。

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

感谢您的基本模块的build议。 不过,我宁愿不为此创build一个新模块。

在Surefire Maven文档和博客中find了可以接受的答案。 另见“ 如何创build一个包含testing类的jar ”。

这将使用jar插件从src/test/java创build代码的jar文件,以便带有testing的模块可以共享代码。

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

为了使用上面创build的附加testingJAR,只需使用指定的testing分类来指定对主构件的依赖关系:

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

我们通过使用testing代码的maven项目作为src / main / java并向项目添加以下依赖项来解决此问题:

  <dependency> <groupId>foo</groupId> <artifactId>test-base</artifactId> <version>1</version> <scope>test</scope> </dependency> 

是的,只是在Main中包含Base模块作为依赖。 如果您只是inheritance了testing代码,那么您可以使用scope标签来确保Maven在部署时不会在代码中包含代码。 像这样的东西应该工作:

 <dependency> <groupId>BaseGroup</groupId> <artifactId>Base</artifactId> <version>0.1.0-SNAPSHOT</version> <scope>test</scope> </dependency>