本文系統梳理 Maven 專案中單元測試執行、報告生成、覆蓋率統計的完整配置方案,涵蓋 maven-surefire-plugin、maven-surefire-report-plugin 及 cobertura-maven-plugin 的進階用法。
Maven 自動識別 src/test/java 下符合以下模式的類為測試類:
Test*.java(以 Test 開頭)*Test.java(以 Test 結尾)*TestCase.java(以 TestCase 結尾)# 跳過測試編譯與執行
mvn package -DskipTests
# 僅跳過執行,仍編譯測試代碼
mvn package -Dmaven.test.skip=true
# 指定運行單個/多個測試類
mvn test -Dtest=AccountImageServiceImplTest
mvn test -Dtest=AccountImageServiceImplTest,AccountImageUtilTest
# 模糊匹配
mvn test -Dtest=*Test
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/AccountImageUtilTest.java</exclude>
</excludes>
</configuration>
maven-surefire-plugin 預設生成 target/surefire-reports 下的 .txt 與 .xml 報告。
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.12.2</version>
<configuration>
<showSuccess>false</showSuccess> <!-- 僅顯示失敗 -->
</configuration>
</plugin>
執行 mvn surefire-report:report 生成 target/site 下的 HTML 報告。
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<formats>
<format>html</format>
<format>xml</format>
</formats>
</configuration>
<executions>
<execution>
<id>cobertura-report</id>
<goals><goal>cobertura</goal></goals>
<phase>test</phase>
</execution>
</executions>
</plugin>
mvn cobertura:cobertura # 生成報告至 target/site/cobertura/index.html
mvn cobertura:clean # 清理舊數據
mvn cobertura:check # 檢查覆蓋率門檻
mvn cobertura:help # 查看幫助
<build>
<plugins>
<!-- 測試執行核心 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<includes><include>**/*Test.java</include></includes>
<excludes><exclude>**/*IntegrationTest.java</exclude></excludes>
</configuration>
</plugin>
<!-- HTML 測試報告 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.12.2</version>
</plugin>
<!-- 覆蓋率報告 -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<formats><format>html</format><format>xml</format></formats>
</configuration>
</plugin>
</plugins>
</build>
target/site/surefire-report.htmltarget/site/cobertura/index.html