一、简介
Cobertura 是一种开源工具,它通过检测基本的代码,并观察在测试包运行时执行了哪些代码和没有执行哪些代码,来测量测试覆盖率。
下载Cobertura http://cobertura.github.io/cobertura/
二、实例
1.新建一个项目junit01,结构如下:
Calculator.java
package com.test.junit;
public class Calculator
{
public int add(int a, int b)
{
return a+b;
}
public int substact(int a, int b)
{
return a-b;
}
public int mutilfy(int a, int b)
{
return a*b;
}
public int divid(int a, int b)
{
if(b == 0)
throw new RuntimeException("/ by zero");
return a/b;
}
public String toString()
{
return this.getClass().getName()+"@"+this.hashCode();
}
}
CalculatorTest.java
package com.test.junit;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class CalculatorTest
{
private Calculator cal;
@Before
public void setUp() throws Exception
{
cal = new Calculator();
}
@Test
public void testAdd()
{
assertEquals("相等", 5, cal.add(2, 3));
}
@Test
public void testSubstact()
{
assertEquals("相等", -1, cal.substact(2, 3));
}
@Test
public void testMutilfy()
{
assertEquals("相等", 6, cal.mutilfy(2, 3));
}
@Test
public void testDivid()
{
assertEquals("相等", 2, cal.divid(6, 3));
}
@Test(expected=RuntimeException.class)
public void testDividByZero()
{
assertEquals("异常", -1, cal.divid(3, 0));
}
}
2.进入工作空间将junit01项目的src、lib以及bin目录拷贝到一个新的文件夹,并将lib和src移动到bin目录下
3.生成代码覆盖率的代码和cobertura.ser文件
cd到bin目录, 命令为: cobertura-instrument.bat --destination instrumented com/test/junit/
将会生成 instrumented和cobertura.ser,而instrumented中包含着class文件
4.根据cobertura.ser文件运行测试(PS:lib中要添加cobertura.jar,slf4j.jar)
在bin目录下,使用命令 java -cp lib/junit-4.11.jar;lib/hamcrest-core-1.3.jar;lib/cobertura-2.1.1.jar;lib/slf4j-api-1.7.5.jar;instrumented;.; -Dnet.sourceforge.cobertura.datafile=cobertura.ser org.junit.runner.JUnitCore com.test.junit.CalculatorTest
5.生成报告
在bin目录下,使用命令 cobertura-report.bat --format html -datafile=cobertura.ser --destination report src
6.查看报告
代码下载:http://download.youkuaiyun.com/detail/zxdfc/9602337