技术开发 频道

JCoverage使用

【IT168 技术文章】

    使用目的
    JCoverage正如其名,主要用于代码的覆盖测试。通过在被测试类的二进制文件中添加相应的指令,再配合junit,jcoverage可以给出被测试类的代码覆盖率,并给出测试过程中哪些语句被执行,哪些没有。通过这些信息,我们可以了解测试代码的测试质量,以及被测试类中哪些语句需要特别的关注(即那些未被覆盖的语句)。

    当前的版本是1.0.5,可以从www.jcoverage.com/downloads.html下载。在实际使用时,需要将jcoverage用到的类放到对应的classpath中。在这个版本中它所依赖的外部类以及版本:

    - bcel    5.1     http://jakarta.apache.org/bcel/

    - log4j   1.2.8    http://jakarta.apache.org/log4j/

    - getopt  1.0.9    http://gnu.org/

    - oro     2.0.7   http://jakarta.apache.org/oro/

    用法
    1.       jcoverage可以和ant配合使用,使这一过程自动化。基本用法:

    -          编译被测试类和相应的被测试类的junit代码。

    -          使用<instrument>,将jcoverage的指令加入到被测试类的二进制文件中。为了保证这一过程能够有效,请在编译被测试类时,设置<javac>的debug属性设为yes。

    -          执行junit代码进行代码覆盖测试。这一步需要注意的是,需要将被注入指令的测试类要早于单元测试所需的测试类装入。为了确保这一点,需要使用<classpath>,使注入指令的测试类位于测试类之前。

    -          使用<report>产生覆盖测试的报告。

    2.       使用例子:

<!-- 采用debug模式编译被测试类 -->

<javac destdir="${dist.coverage.classes}" deprecation="on" debug="yes">

<src path="${src.code}"/>

    <classpath refid="classpath"/>

</javac>

<!-- 编译被测试类的junit代码 -->

<javac destdir="${dist.coverage.junit}" deprecation="on">

    <src path="${src.junit}"/>

    <classpath refid="classpath"/>

</javac>

<!-- 定义jcoverage任务 -->

<path id="jcoverage">

        <fileset dir="junit_lib">

               <include name="jcoverage.jar"/>

        </fileset>

    </path>

<taskdef classpathref="jcoverage" resource="tasks.properties"/>

<!-- 给被测试类二进制代码中注入jcoverage的指令 -->

<instrument todir="${dist.coverage.instrument}">

        <classpath refid="classpath"/>

    <!-- 忽略org.apache.common的应用 -->

    <ignore regex="org.apache.common.*"/>

 

    <fileset dir="${dist.coverage.classes} ">

        <include name="**/*.class"/>

    </fileset>

</instrument>

<!-- 启动junit,进行代码覆盖测试 -->

<junit printsummary="yes" haltonfailure="no" fork="yes">

    <classpath>

        <!-- 注意:被注入指令的类,位置在测试类之前。

这样确保它们早于测试类备加载,使指令起作用。 -->

        <pathelement location="${dist.coverage.instrument}"/>

        <path refid="classpath"/>

        <pathelement location="${dist. coverage.junit}"/>

    </classpath>

 

    <formatter type="xml"/>

 

        <batchtest todir="${doc.jcoverageReport}">

         <fileset dir="${src.junit}" includes="**/*Test.java" />

     </batchtest>

</junit>

<!-- 产生代码覆盖测试报告 -->

<report srcdir="${src.code}" destdir="${doc.jcoverageReport}">

0
相关文章