在我的 Maven 项目中,我有许多模块。是否可以通过命令行选项关闭某些模块的运行单元测试?
我的项目大约需要 15 分钟才能完成所有单元测试。我想通过仅运行我正在处理的模块中的单元测试来加快整体构建速度。我不想进入并编辑每个单独的 pom.xml 来实现此目的。
我已经尝试了这里概述的解决方案:我可以通过maven运行特定的testng测试组吗?但是结果是我想跳过的模块中存在很多测试失败。我认为“组”与模块的概念不同?
要打开和关闭整个项目的单元测试,请使用 Maven Surefire 插件的跳过测试功能。从命令行使用skipTests 有一个缺点。在多模块构建场景中,这将禁用所有模块的所有测试。
如果您需要对运行模块的测试子集进行更细粒度的控制,请考虑使用 Maven Surefire 插件的测试包含和排除功能。
要允许命令行覆盖,请在配置 Surefire 插件时使用 POM 属性。以以下 POM 段为例:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<excludes>
<exclude>${someModule.test.excludes}</exclude>
</excludes>
<includes>
<include>${someModule.test.includes}</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<someModule.skip.tests>false</someModule.skip.tests>
<skipTests>${someModule.skip.tests}</skipTests>
<someModule.test.includes>**/*Test.java</someModule.test.includes>
<someModule.test.excludes>**/*Test.java.bogus</someModule.test.excludes>
</properties>
使用上述 POM,您可以通过多种方式执行测试。
mvn test
mvn -DskipTests=true test
mvn -DsomeModule.skip.tests=true test
mvn -DsomeModule.test.includes="**/*IncludeTest.java" test
mvn -DsomeModule.test.excludes="**/*ExcludeTest.java" test
找到了一种在命令行上排除的方法:
# Exclude one test class, by using the explanation mark (!)
mvn test -Dtest=!LegacyTest
# Exclude one test method
mvn verify -Dtest=!LegacyTest#testFoo
# Exclude two test methods
mvn verify -Dtest=!LegacyTest#testFoo+testBar
# Exclude a package with a wildcard (*)
mvn test -Dtest=!com.mycompany.app.Legacy*
…如果你想将参数传递给 Hudson/Jenkins 中的 Maven 发布插件,你必须使用
-Darguments=-DskipTests
让它发挥作用。
如果你想使用 Maven 配置文件:
你可能想让它工作做这样的事情:
我不知道是否有支持的命令行选项具有相同的功能。
您也可以尝试直接使用环境属性,如本文档页面所示:
即像这样的东西:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<skipTests>${moduleA.skipTests}</skipTests>
</configuration>
</plugin>
然后使用
mvn -DmoduleA.skipTests=false test
测试该模块。