使用Cobertura计算代码覆盖率
软件测试过程中需要计算代码覆盖率,使用cobertura过程中对于这个工具的计算结果感到疑惑,于是自己动手实践了一下。
把pom.xml中的注释打开
修改了一下demo的HelloWorld.java与HelloWorldTest.java。
package com.test.jacoco;
public class HelloWorld {
public HelloWorld() {
}
public String sayHi() {
return "Hello World";
}
public int minusNum(int a, int b)
{
if (a < b)
{
int c = b - a;
System.out.println(c);
return c;
}
else if (a==b) {
return 0;
}
else
{
return a - b;
}
}
public int addNum(int a, int b) {
if (a > b) {
int c = 5;
System.out.print(c);
}
else if (a == b)
{
int c = 6;
System.out.println(c);
}
/*
* word
* word
*
*
* */
else
{
/*
* a
* b
* c
*
* */
int c = 7;
System.out.println(c);
}
return a + b;
}
}
package com.test.jacoco.test;
import junit.framework.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import com.test.jacoco.HelloWorld;
public class HelloWorldTest {
@Test
public void testMethod1() {
HelloWorld hw = new HelloWorld();
String word = hw.sayHi();
assertEquals(word, "Hello World");
}
@Test
public void testMethod2() {
HelloWorld hw = new HelloWorld();
int num = hw.addNum(1, 3);
assertEquals(num, 4);
}
@Test
public void testMethod3() {
HelloWorld hw = new HelloWorld();
int num = hw.addNum(1, 1);
assertEquals(num, 2);
}
@Test
public void testMethod4() {
HelloWorld hw = new HelloWorld();
int num = hw.addNum(3, 1);
assertEquals(num, 4);
}
@Test
public void testMethod5() {
HelloWorld hw = new HelloWorld();
int num = hw.minusNum(3, 1);
assertEquals(num, 2);
}
}
在项目根目录输入
mvn cobertura:cobertura
然后在 ~/target/site/cobertura中打开index.html
整体结果
实际情况
根据这个demo,可以看到Cobertura统计coverage的方法不是直观上的计算行数。实际上是对编译后的class进行插桩。
在Defects4J数据集上,以Lang-1-f为例子,modified class为org.apache.commons.lang3.math.NumberUtils,源代码有1436行,但是Cobertura工具统计出来的结果为373/380。