Wednesday, November 5, 2008

Code Coverage - Cobertura

Recently I evaluated the various open source code coverage tools and out of all I was really amazed by the simplicity and the reporting styles of this tool.

Based on the Jcoverage, Cobertura provides the integration with the ANT and Maven.

The Code coverage reports can be generated in just 2 steps:-

1. Instrument the java Files - Cobertura weaves the .class files (also jars) and add counters to the classes for which we need to evaluate the code coverage. In order to exclude the Test classes form the Code coverage we need to provide the filters in the ant target.
The output of this activity is the cobertura.ser file which contains the information about the all weaved files and their respective counters.
Now whenever the test cases are executed and they execute the various lines of .class file, cobertura increase the counter in the cobertura.ser file.

<target name="instrument">
<echo message="${classes.dir}"/>
<cobertura-instrument todir="${build.classes.dir}">
<fileset dir="${build.classes.dir}">
<include name="**/*.class">
<exclude name="**/*Test.class"/>
<exclude name="**/Test*.class"/>
<exclude name="**/*Test*.class"/>
</fileset>
</cobertura-instrument>
</target>

2. Report Generation - Generate the report by using "cobertura-report" target. Make sure the cobertura.ser file is there in the same directory from where the Test cases are executed.

<target name="coverage">
<mkdir dir="codeCoverageReport"/>
<cobertura-report format="html" destdir="codeCoverageReport" datafile="path of the cobertura.ser file">
<!-- including sources-->
<fileset dir="../../">
<include name="**/*.java" />
</fileset>
<fileset dir="../../../">
<include name="**/*.java" />
</fileset>
</cobertura-report>

</target>


Merging of .ser files

Cobertura also provide the Ant target to merge various .ser file and create One Single .ser file.

<target name="merge">
<copy todir="path of the directory where we need to keep the merged file" file="name of the file to be merged"/>
<cobertura-merge datafile="path of the .ser file which will contain all the merged changes" maxmemory="512m">
<!-- Merging Core .ser filed-->
<fileset dir="${project.home}/main/src/api">
<include name="cobertura.ser" />
</fileset>
<!-- Merging net .ser files-->
<fileset dir="${project.home}/main/src/impl">
<include name="cobertura.ser" />
</fileset>
</cobertura-merge>
</target>

No comments: