用 Cobertura 测量代码测试覆盖率

Cobertura是一个基于jcoverage的免费Java工具,它能够显示哪一部分代码被你的测试所覆盖,并可生成HTML或XML报告.

 

cobertura 的大概基本工作思路:
1.对已经编译好的class 文件添加标记
2. 对添加好标记的代码进行单元测试
3. 输出覆盖率统计报告

在ant 中使用cobertura 的基本步骤:
1. 编译代码
2. 定义cobertura 的ant task
3. 用nstrument 命令为编译好的代码添加标记
4. 用junit 命令对添加好标记的代码进行单元测试
5. 用cobertura-report 命令输出报告

 

编译代码:

<target name="compile">
        <ant antfile="build.xml" inheritAll="false" target="compile"/>
 </target>
 

在 build.xml 文件中添加一个任务定义:

 

<path id="cobertura.classpath">
        <fileset dir="${lib.dir}">
            <include name="cobertura/*.jar"/>
        </fileset>
        <pathelement location="${cobertura.instrumented.classes.dir}"/>
    </path>

    <taskdef classpathref="cobertura.classpath" resource="tasks.properties"/>

 

添加一个instrument 任务,该任务将在已经编译好的类文件中添加标记。todir 属性指定将测量类放到什么地方。fileset 子元素指定测量哪些 .class文件:

<target name="instrument" depends="compile">
        <cobertura-instrument todir="${cobertura.instrumented.classes.dir}">
            <fileset dir="${build.src.dir}">
                <include name="**/*.class"/>
                <exclude name="**/web/**/*.class"/>
                <exclude name="**/constant/*.class"/>
                <exclude name="**/*Test.class"/>
            </fileset>
        </cobertura-instrument>
    </target>

 可以排除一些不需要检查的class文件。

运行测试:

<target name="cover-test" depends="instrument">
        <mkdir dir="${cobertura.report.dir}"/>
        <junit fork="true" failureproperty="unit.tests.failed" printsummary="true" showoutput="yes">
            <classpath>
                <!--
                   Note the classpath order: instrumented classes are before the
                   original (uninstrumented) classes.  This is important.
               -->
                <path refid="cobertura.classpath"/>
                <path refid="test.classpath"/>
            </classpath>
            <formatter type="xml"/>
            <batchtest todir="${cobertura.report.dir}">
                <fileset dir="${build.unittest.dir}">
                    <include name="**/*Test.class"/>
                </fileset>
                <fileset dir="${build.functionaltest.dir}">
                    <include name="**/*Test.class"/>
                </fileset>
                <fileset dir="${build.integrationtest.dir}">
                    <include name="**/*Test.class"/>
                </fileset>
            </batchtest>
        </junit>
    </target>
 

最后,生成测试测量报告:

<target name="coverage-report" depends="cover-test">
        <cobertura-report format="html" destdir="${cobertura.report.dir}" srcdir="${src.dir}"/>
    </target>
 

生成的报告形式大概如下:

 

测量效果图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值