自動化單元測試,通過maven-surefire-plugin于主流單元測試框架junit3,junit4及TestNG集成。
一、maven-surefire-plugin簡介
Maven不是一個單元測試框架,主流測試框架是junit,TestNG。Maven所作的是在構(gòu)建執(zhí)行到特定生命周期階段,通過maven-surefie-plugin來執(zhí)行JUnit或TestNG的測試用例。maven-surefie-plugin,可以稱之為測試運行器。
默認情況下,maven-surefire-plugin的test目標會自動執(zhí)行測試源碼路徑下所有符合一組命令模式的測試類,模式為:
- */Test.java:任何子目錄下所有以Test開頭的Java類
- */Test.java
- */TestCase.java
將測試類按上述模式命名,Maven就能自動運行他們。
三、跳過測試
在命令行加入?yún)?shù)skipTests可以跳過測試:
mvn package-DskipTests。
也可以在maven-surefire-plugin配置,不推薦。
...
<configuration>
<skipTests>true</skipTests>
</configuration>
...
還運行臨時性的跳過測試代碼的編譯:mvn package-Dmaven.test.skip=true。不推薦。也可以在插件中配置skip為true。
四、動態(tài)指定運行的測試用例
maven-surefire-plugin提供一個test參數(shù)讓Maven用戶在命令行指定要運行的測試用例。例如,只想運行RandomGeneratorTest,使用:mvn test-Dtest=RandomGeneratorTest。test參數(shù)支持符號匹配,使用逗號指定多個測試用例。
test參數(shù)必須匹配一個或多個測試類,如果插件找不到匹配的測試類,會報錯并構(gòu)建失敗。-DfailIfNoTests=false,告訴插件即使沒有任何測試也不報錯。
五、包含與排除測試用例
使用includes、include包含測試類。
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.5</version>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>
</configuration>
</plugin>
使用excludes、exclude排除測試類。
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.5</version>
<configuration>
<excludes>
<exclude>**/*Tests.java</exclude>
</excludes>
</configuration>
</plugin>
六、測試報告
1.基本測試報告
默認,maven-surefire-plugin會在項目的target/surefire-reports目錄下生成兩種格式的錯誤報告:
- 簡單文本格式
- 與JUnit兼容的XML格式
2.測試覆蓋率報告
Cobertura——測試覆蓋率統(tǒng)計工具,Maven通過cobertura-maven-plugin與之集成,可以使用簡單命令生成測試覆蓋率報告:mvn cobertura:cobertura。
七、運行TestNG測試
在POM中加入TestNG依賴。

TestNG運行用戶使用testng.xml文件配置想運行的測試集合。
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite1" verbose="1">
<test name="Regression1">
<classes>
<class name="xx.xx.xx.xxx"/>
</classes>
</test。
</suite>
同時配置maven-surefire-plugin使用該testng.xml:
<plugin>
...
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
TestNG支持測試組概念:@Test=(group=(“unit”,“medium”))??梢栽诓寮信渲枚鄠€測試組。
<plugin>
...
<configuration>
<groups>unit,medium</groups>
</configuration>
</plugin>
八、重用測試代碼
配置maven-jar-plugin將測試類打包:
<plugin>
<groupId>org.apache.maven.plugin</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goal>test-jar</goal>
</execution>
</executions>
</plugin>
maven-jar-plugin有兩個目標,分別是jar、test-jar,前者內(nèi)置綁定在default生命周期的package階段,其行為是對項目主代碼打包,后者沒有內(nèi)置綁定,需要顯式聲明該目標來打包測試代碼。test-jar默認綁定生命周期階段為package。
通過依賴聲明使用測試包構(gòu)建。
<dependency>
<groupId>xxxx</groupId>
<artifactId>xxxx</artifactId>
<version>1.0.0-SNAPSHOT</type>
<type>test-jar</type>
<scope>test</scope>
</dependency>