pom中添加Junit依賴
<!-- Junit -->
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
測試類
package com.glen.he; public class ComplexCalculation { public int Division(int a, int b) { return (a / b); } public int Multiply(int a, int b) { return (a * b); } }
package com.glen.he; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ComplexCalculationTest { ComplexCalculation cc = new ComplexCalculation(); @Test public void DivisionTest() { int c = cc.Division(100, 5); assertEquals(20, c); } @Test public void MultiplyTest() { int c = cc.Multiply(100, 5); assertEquals(500, c); } }
(先配置idea中terminal maven的環境變量)執行mvn test
Maven Surefire Plugin+Junit測試
在默認情況下,執行maven test/maven package/maven install命令時會在target/surefire-reports目錄下生成txt和xml格式的輸出信息
其實maven也可以生成html格式的報告,只需要用一個插件即可:maven-surefire-report-plugin
pom.xml中添加插件
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.5</version>
<configuration>
//跳過測試
<skipTests>true</skipTests>
//排除測試
<excludes>
<exclude>**/*ServiceTest.java</exclude>
</excludes>
//執行測試以 Test.java 或 TestCase.java 結尾的文件
<includes>
<include>**/*Test.java</include>
<include>**/*TestCase.java</include>
</includes>
</configuration>
</plugin>
1.先編譯源文件和測試用例
2.再調用surefire插件(這個插件主要是用來執行單元測試的插件)生成txt和xml個數的測試輸出信息
3.surefire報告插件(也就是maven-surefire-report-plugin)會把target/surefire-reports下的所有xml報告轉換成html格式的文件。並將這個html格式的測試報告保存在target/site目錄下
Jacoco
pom.xml添加插件
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.3</version>
<configuration>
<skip>false</skip>
</configuration>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<!-- 指定報告輸出目錄 -->
<configuration>
<outputDirectory>${basedir}/target/coverage-reports</outputDirectory>
</configuration>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
直接啟動下圖1會生成測試報告.html 和 覆蓋率報告.html
target下的jacoco.exec文件也可以通過下圖中的方式查看覆蓋率報告
說明:綠色 覆蓋
紅色 未執行覆蓋
Maven動態指令測試用例
mvn test -Dtest=類名 //執行單個測試類
mvn test -Dtest=類名,類名 //逗號或* 分割執行多個測試類
命令:mvn test surefire-report:report -Dmaven.test.skip=true 執行生成html文件
mvn cobertura:cobertura 生成覆蓋率報告