使用Cobertura的命令行方式测试代码覆盖率

本文介绍了如何使用Cobertura这个开源工具进行代码覆盖率测试。首先,下载Cobertura并创建一个项目,接着详细阐述了从生成覆盖率代码到运行测试、生成报告的步骤。通过在命令行中执行特定指令,可以完成对Java项目测试覆盖率的计算,并生成详细的报告。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

一、简介   

           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

参考资料 http://www.ibm.com/developerworks/cn/java/j-cobertura/

               http://www.icoolxue.com/play/701

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值