您的位置:首页 > 编程语言

单体测试的代码覆盖率工具cobertura

2009-08-15 14:43 477 查看
单体测试的时候,覆盖率在很多工程中都是一个比较重要的指标。客户验收的时候想看覆盖率指标的时候怎么办呢?
肯定是比较简单,直观的报告书比较好。cobertura(http://cobertura.sourceforge.net/index.html)
就是一个能够自动实现测试覆盖率的工具。
这个工具的开发人据说是一个法国人,所以工具名字比较拗口。
什么是cobertura呢?
"Cobertura is my new coverage tool of choice, and I hope to give something back. I hope you'll get involved, too."
cobertura有3中方式,Ant Tasks ,Command-line 和Maven 。
这里简单介绍一下在ant中的实现。
首先下载必要的jar。下面的jar有的不是最新的。
cobertura.jar
lib/asm-2.2.1.jar
lib/asm-tree-2.2.1.jar
lib/jakarta-oro-2.0.8.jar
lib/log4j-1.2.9.jar
在build文件中增加任务,配置环境信息。
<path id="cobertura.classpath">
<fileset dir="${cobertura.dir}">
<include name="cobertura.jar" />
<include name="lib/**/*.jar" />
</fileset>
</path>
<taskdef classpathref="cobertura.classpath" resource="tasks.properties" />
在build文件中追加cobertura-instrument任务
<target name="instrument">
<cobertura-instrument todir="${instrumented.classes.dir}">
<fileset dir="${classes.dir}">
<include name="**/*.class" />
<exclude name="**/*Test.class" />
</fileset>
</cobertura-instrument>
</target>
单体测试。一种是JUNIT测试。另外就是对tomcat启动的参数追加cobertura的SER包信息,并在servlet终极的时候调用写入信息。
对测试结果生成报表。执行在build文件中的coverage-report任务即可。 format="html"设置报表的格式。
<target name="coverage-report">
<cobertura-report format="html" destdir="${cobertura.report}">
<fileset dir="${src.dir}">
<include name="**/*.java" />
</fileset>
</cobertura-report>
</target>
如果在多台服务器上测试的话,还可以把测试结果合并进去。合并方法是执在build文件中的cobertura-merge任务。只要把要合并的SER加入任务中即可。
<cobertura-merge>
<fileset dir="${test.execution.dir}">
<include name="server1/cobertura.ser" />
<include name="server2/cobertura1.ser" />
<include name="server2/cobertura2.ser" />
</fileset>
</cobertura-merge>
这个合并任务我感觉特别好,特别是多个公司开发的时候,如果想了解总体的测试状况的话,就把各个公司所测试的结果的SER文件做合并处理。然后对生成的合并SER文件执行coverage-report就可以了。
在自己实现的Servlet类中destroy方法中加入下面的代码。tomcat停止的时候就会写入测试数据。

public void destroy() {
// Cobertura 用
try {
String className = "net.sourceforge.cobertura.coveragedata.ProjectData";
String methodName = "saveGlobalProjectData";
Class saveClass = Class.forName(className);
java.lang.reflect.Method saveMethod = saveClass.getDeclaredMethod(
methodName, new Class[0]);
saveMethod.invoke(null, new Object[0]);
} catch (Throwable t) {
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: