Visit me elsewhere:

Setting up Cobertura Java Code-Coverage with Netbeans

We use Cobertura as our Code-Coverage Tool for a Java project and I had to somehow integrate it into Netbeans. This Blogpost helped me do it, pretty good.

In Short:

build.xml is your ant-build file, it also includes the Netbeans default-, auto-generated one nbproject/build-impl.xml

The nbproject/project.properties file is used for variable-definitions for usage in the build file.

In build.xml inside the <project>-Tag, add:

<path id="cobertura.classpath">
  <fileset dir="${basedir}">
    <include name="lib/cobertura-1.9.4.1/cobertura.jar" />
    <include name="lib/cobertura-1.9.4.1/lib/*\*/\*.jar" />
  </fileset>
</path>
<taskdef classpathref="cobertura.classpath" resource="tasks.properties"/>
<target name="cobertura-instrument" depends="init,compile-test,-pre-test-run">
  <cobertura-instrument todir="${build.test.cobertura.classes.dir}">
  <fileset dir="${build.classes.dir}">
  <include name="*\*/\*.class"/>
  </fileset>
  </cobertura-instrument>
</target>
<target name="test-coverage" depends="init,compile-test,-pre-test-run,cobertura-instrument,-do-test-run,test-report,-post-test-run,-test-browse"/>
<target name="cobertura-coverage-report" depends="init">
  <cobertura-report srcdir="${src.dir}" destdir="${cobertura.report.dir}"/>
  <delete file="Serialized" failonerror="false"/>
  <delete file="cobertura.ser" failonerror="false"/>
</target>

This gives you the necessary build-targets. But you just used some variables which were not set yet! So:

In your nbproject/project.properties:

build.test.cobertura.classes.dir=${build.dir}/cobertura-instrumented-classes
cobertura.dir=lib/cobertura-1.9.4.1
cobertura.report.dir=${build.dir}/cobertura-report

and extend the following 2:

run.test.classpath=\
  ${cobertura.dir}/cobertura.jar:\
  ${build.test.cobertura.classes.dir}:\
  ${javac.test.classpath}:\
  ${build.test.classes.dir}
…

With this in netbeans you can switch to the Files-window, right-click the build.xml, choose Run Target, then choose (under Other) test-coverage and afterwards cobertura-coverage-report to generate the HTML report in your build folder.

For our project, I afterwards added an exclude for the GUI-package (in the cobertura-instrument-target), which is not to be tested anyway, so code coverage is a dont-want there:

<target name="cobertura-instrument" depends="init,compile-test,-pre-test-run">
  <cobertura-instrument todir="${build.test.cobertura.classes.dir}">
    <fileset dir="${build.classes.dir}">
      <include name="**/*.class"/>
      <exclude name="<em>~ourprojectname~</em>/gui/**/*.class"/>
    </fileset>
  </cobertura-instrument>
</target>