JaCoco是一個代碼覆蓋率庫。
官方網(wǎng)站:http://www.jacoco.org/
安裝:
以 Maven(http://www.testclass.net/maven/) 安裝為例:
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.9</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
使用:
Maven項目目錄如下:

image
創(chuàng)建被測試類
Count.java
public class Count {
/**
* 計算并返回兩個參數(shù)的和
*/
public int add(int x ,int y){
return x + y;
}
/**
* 計算并返回兩個參數(shù)的和
*/
public int sub(int x ,int y){
return x - y;
}
}
代碼很簡單,這里不做過多解釋。
接下來創(chuàng)建測試類CountTest.java。
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.assertEquals;
public class CountTest {
@Test
public void testAdd() {
Count count = new Count();
int result = count.add(2,2);
assertEquals(result, 4);
}
}
通過TestNG單元測試框架來運(yùn)行測試用例,注意這里只編寫了針對Count類的add()方法進(jìn)行測試。
運(yùn)行:
切換到j(luò)acocoTest項目根目錄下,執(zhí)行mvn install命令。

image
查看:
切換到項目下的“\target\site\jacoco\”目錄,打開 index.html文件。

image

image
通過JaCoCo工具分析可以清楚地看哪些代碼被執(zhí)行了,而哪些未被執(zhí)行。