用通常运行测试包的同一种类型的 Ant 任务运行测试。惟一的区别在于:被测量的类必须在原始类出现在类路径中之前出现在类路径中,而且需要将 Cobertura JAR 文件添加到类路径中:
请<target name="cover-test" depends="instrument"> <mkdir dir="${testreportdir}" /> <junit dir="./" failureproperty="test.failure" printSummary="yes" fork="true" haltonerror="true"> <!-- Normally you can create this task by copying your existing JUnit target, changing its name, and adding these next two lines. You may need to change the locations to point to wherever you've put the cobertura.jar file and the instrumented classes. --> <classpath location="cobertura.jar"/> <classpath location="target/instrumented-classes"/> <classpath> <fileset dir="${libdir}"> <include name="*.jar" /> </fileset> <pathelement path="${testclassesdir}" /> <pathelement path="${classesdir}" /> </classpath> <batchtest todir="${testreportdir}"> <fileset dir="src/java/test"> <include name="**/*Test.java" /> <include name="org/jaxen/javabean/*Test.java" /> </fileset> </batchtest> </junit> </target>> |
Jaxen 项目使用 JUnit 作为其测试框架,但是 Cobertura 是不受框架影响的。它在 TestNG、Artima SuiteRunner、HTTPUni 或者在您自己在地下室开发的系统中一样工作得很好。
最后,cobertura-report 任务生成本文开始部分看到的那个 HTML 文件:
<target name="coverage-report" depends="cover-test"> <cobertura-report srcdir="src/java/main" destdir="cobertura"/> </target> |
srcdir 属性指定原始的 .java 源代码在什么地方。destdir 属性指定 Cobertura 放置输出 HTML 的那个目录的名称。
在自己的 Ant 编译文件中加入了类似的任务后,就可以通过键入以下命令来生成一个覆盖报告:
% ant instrument % ant cover-test % ant coverage-report |
当然,如果您愿意的话,还可以改变目标任务的名称,或者将这三项任务合并为一个目标任务。
结束语
Cobertura 是敏捷程序员工具箱中新增的一个重要工具。通过生成代码覆盖率的具体数值,Cobertura 将单元测试从一种艺术转变为一门科学。它可以寻找测试覆盖中的空隙,直接找到 bug。测量代码覆盖率使您可以获得寻找并修复 bug 所需的信息,从而开发出对每个人来说都更健壮的软件。