一、maven-surefire-plugin简介
maven-surefire-plugin支持JUnit和TestNG。默认情况下,maven-surefire-plugin的test目标会自动执行测试源码路径下所有以Test开头、Test或TestCase结尾的的Java类。
二、跳过测试
如果想跳过测试阶段,可用:
mvn package -DskipTests
想临时性跳过测试代码的编译,可用:
mvn package -Dmaven.test.skip=true
maven.test.skip同时控制maven-compiler-plugin和maven-surefire-plugin两个插件的行为,即跳过编译,又跳过测试。
三、手动指定测试用例
maven-surefire-plugin的test参数用来指定要运行的测试用例:
//指定测试类
mvn test -Dtest=RandomGeneratorTest
//以Random开头,Test结尾的测试类
mvn test -Dtest=Random*Test
//用逗号分隔指定多个测试用例
mvn test -Dtest=ATest,BTest
test参数必须匹配至少一个测试类,否则会报错并导致构建失败。此时可使用:
mvn test -Dtest -DfailIfNoTests = false
来指定即使没有任何测试用例也不要报错。
四、包含与排除测试用例
<plugin>
<groupId>org.apahce.maven.plugins<groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.5</version>
<configuration>
<includes>
<include>** / *Tests.java</include>
</includes>
</configuration>
</plugin>
使用** / * Test.java 来匹配所有以Tests结尾的Java类。两个星号**用来匹配任意路径,一个星号*用来获取除路径风格符外的0个或多个字符。还可使用excludes来排除一些测试类。
五、测试报告
1.基本的测试报告
默认情况下,maven-surefire-plugin会在项目的target/surefire-reports目录下生成两种格式的错误报告:
- 简单文本格式
- 与JUnit兼容的XML格式
XML可用Eclipse的JUnit插件打开?
2.测试覆盖率报告
Cobertura是一个用来测试覆盖率统计工具。Maven通过cobertura-maven-plugin插件与之集成,命令如下:
mvn cobertura:cobertura
六、运行TestNG测试
TestNG支持使用xml来配置要运行的测试用例。可用:
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testing.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
TestNG还支持测试组
<configuration>
<groups>util,medium</groups>
</configuration>
七、重用测试代码
通过配置maven-jar-plugin将测试类打包
<plugin>
<groupId>org.apahce.maven.plugins<groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
打包后可以声明依赖:
<groupId></groupId>
<artifactId></artifactId>
<version></version>
<type>test-jar</type>
<scope>test</scope>