maven-surefire-plugin 是在 maven 生命周期中,test
阶段的内置插件,用来专门做 exclude 等控制用的。
相信大家都很清楚 maven-surefire-plugin 在 pom.xml 里面配置的用法,通过配置来 exclude、include 指定的 unit test(支持通配符 * )。简单展示:
<project>
[...]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<excludes>
<exclude>**/TestCircle.java</exclude>
<exclude>**/TestSquare.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
[...]
</project>
但是现在出现了一个问题:在我的 jenkins 进行自动部署过程中,分开了 uat deploy 和 prd deploy。 在 uat deploy 时候,需要通过外部传参的方式进行 unit test 的控制。翻看了一下 maven official document。发现 maven-surefire-plugin 也是可以通过 command line 的方式来控制的。
now, let me show you the code:
# 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*
(reference: https://blog.jdriven.com/2017/10/run-one-or-exclude-one-test-with-maven/)
当然也可以直接在 install phase 进行 exclude:
eg.
mvn install -Dtest=Class,!Class#function
更多的介绍可以直接看 official document:
[https://maven.apache.org/surefire/maven-surefire-plugin/examples/single-test.html]