如果您有一个大型的多模块项目,并且您希望仅在某些模块中跳过测试,而无需使用自定义配置和分析更改每个模块 pom.xml 文件,您可以将以下内容添加到父级pom.xml文件:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.12</version>
<executions>
<execution>
<id>regex-property</id>
<goals>
<goal>regex-property</goal>
</goals>
<configuration>
<name>maven.test.skip</name>
<value>${project.artifactId}</value>
<regex>(module1)|(module3)</regex>
<replacement>true</replacement>
<failIfNoMatch>false</failIfNoMatch>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<modules>
<module>module1</module>
<module>module2</module>
<module>module3</module>
</modules>
感谢build-helper-maven-plugin,您实际上会在构建期间通过project.artifactId 属性(在构建期间指向每个artifactId 模块)动态检查您是否在某个模块中,然后正则表达式将为某些值(您要跳过测试的模块名称)寻找匹配并相应地填充maven.test.skip 属性(将其设置为true)。
在这种情况下,module1 和 module3 的测试将被跳过,而 module2 的测试将正常运行,即如正则表达式所示。
这种方法的优点是使其动态和集中(在父级pom.xml 中),因此更便于维护:您可以随时通过更改上面的简单正则表达式来添加或删除模块。
显然,如果这不是构建的默认行为(推荐的情况),您总是可以将上面的 sn-p 包装在 maven profile 中。
您还可以更进一步,根据您的输入进行动态行为:
<properties>
<test.regex>none</test.regex>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.12</version>
<executions>
<execution>
<id>regex-property</id>
<goals>
<goal>regex-property</goal>
</goals>
<configuration>
<name>maven.test.skip</name>
<value>${project.artifactId}</value>
<regex>${test.regex}</regex>
<replacement>true</replacement>
<failIfNoMatch>false</failIfNoMatch>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
在这里,我们实际上是用属性test.regex 替换正则表达式值,默认值为none(或者任何不匹配任何模块名称的值,或者也需要默认跳过匹配项)。
然后从命令行我们可以有
mvn clean test -Dtest.regex="(module1)" > will skip tests only for module1
mvn clean test -Dtest.regex="(module1)|(module2)" > will skip tests on module1 and module2
mvn clean test -Dtest.regex="(module1)|(module2)|(module3)" > will skip the three module tests
mvn clean test -Dtest.regex=".+" > will skip all module tests
mvn clean test > would not skip anything (or fall back on default behavior)
也就是说,然后在运行时由您决定,无需更改 pom.xml 文件或激活任何配置文件。