JaCoco是一个代码覆盖率库。
安装:
org.testng
testng
6.11
test
org.apache.maven.plugins
maven-surefire-plugin
2.18.1
org.jacoco
jacoco-maven-plugin
0.7.9
prepare-agent
report
prepare-package
report
org.apache.maven.plugins
maven-compiler-plugin
3.5.1
1.7
1.7
使用:
Maven项目目录如下:
image
创建被测试类
Count.java
public class Count {
/**
* 计算并返回两个参数的和
*/
public int add(int x ,int y){
return x + y;
}
/**
* 计算并返回两个参数的和
*/
public int sub(int x ,int y){
return x - y;
}
}
代码很简单,这里不做过多解释。
接下来创建测试类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单元测试框架来运行测试用例,注意这里只编写了针对Count类的add()方法进行测试。
运行:
切换到jacocoTest项目根目录下,执行mvn install命令。
image
查看:
切换到项目下的“\target\site\jacoco\”目录,打开 index.html文件。
image
image
通过JaCoCo工具分析可以清楚地看哪些代码被执行了,而哪些未被执行。