About Hebert Coelho

Senior Java Development, with 4 certifications and a published book about JSF (portuguese only). Founder of the blog uaiHebert.com visited from more than 170 different countries.

Covering your tests with Cobertura, JUnit, HSQLDB, JPA

Hello, how are you?

Let us talk today about a very useful tool named “Cobertura”. This framework has the same functions of the Emma framework that we saw in another post.

The major difference between Cobertura and Emma is that Cobertura displays the resume page with graphics.

If you want to see the other topics about this subject click on the links: Coverage of tests with JUnit Ant and Emma // JUnit with HSQLDB, JPA and Hibernate // TDD – First Steps.

I will use the same code from this post (JUnit with HSQLDB, JPA and Hibernate); if you want to set up an environment to run the code you can follow the steps that you will find there (you will find the source code to download at the end of this article).
I am not a skilful Ant user and you may see some code and think “this script is not good”. Fell free to give me ideas of how to “upgrade” the ant code. ;)

Let us do the download of the Cobertura libraries – Download1.9.4.1

After the download finishes put the jar files (/cobertura.jar, /lib/* that includes asm, jakarta, log4j) inside the lib folder of our project.

In the root source of our project create a file named “build.xml” with the following code (the created file needs to be in the root of your project or your project will not work):

<project name="Cobertura Coverage" basedir=".">
 
    <!--  Project Source  Code -->
    <property name="src.dir" value="src" />
    <property name="build.dir" value="bin" />
    <property name="teste.dir" value="src/test" />
    <property name="lib.dir" value="lib" />
    <property name="report.dir" value="cobertura" />
 
    <!-- Project classpath -->
    <path id="project.classpath">
        <pathelement location="${bin.dir}" />
        <fileset dir="${lib.dir}">
            <include name="*.jar" />
        </fileset>
    </path>
 
    <!-- Tested Class -->
    <property name="DogFacadeTest" value="test.com.facade.DogFacadeTest" />
 
</project>

In the code above we are creating the paths to the source codes and to the libraries. Let us create a task to delete the files generated by the Cobertura and the compilated Java source code.

<!-- Clears the paths -->
<target name="01-CleannUp" description="Remove all generated files.">
    <delete dir="${build.dir}" />
    <delete file="cobertura.ser" />
    <delete dir="${report.dir}" />
 
    <mkdir dir="${build.dir}" />
    <mkdir dir="${report.dir}" />
</target>

To compile our source code, add the code bellow and run the task (be sure that the code will compile):

<!-- Compiles the Java code -->
<target name="02-Compile" depends="01-CleannUp" description="invoke compiler">
    <javac debug="true" debuglevel="vars,lines,source" srcdir="${src.dir}" destdir="${build.dir}">
        <classpath refid="project.classpath" />
    </javac>
    <copy file="${src.dir}/META-INF/persistence.xml" todir="${build.dir}/META-INF" />
</target>

Let us setup the Cobertura so it may instrument the tests class and get the environment ready:

<!-- Cobertura configs -->
<property name="cobertura.instrumented-classes.dir" value="${report.dir}/instrumented-classes" />
<property name="cobertura.data.file" value="cobertura.ser" />
<path id="cobertura.classpath">
    <fileset dir="${lib.dir}" includes="/*.jar" />
</path>
 
<!-- Points to the cobertura jar -->
<taskdef classpath="${lib.dir}/cobertura.jar" resource="tasks.properties" classpathref="cobertura.classpath" />
 
<!-- Instruments the classes -->
<target name="03-Instrument" depends="02-Compile">
    <delete quiet="false" failonerror="false">
        <fileset dir="${cobertura.instrumented-classes.dir}" />
    </delete>
    <delete file="${cobertura.data.file}" />
    <cobertura-instrument todir="${cobertura.instrumented-classes.dir}">
        <fileset dir="${build.dir}">
            <include name="**/*.class" />
            <exclude name="**/*Test.class" />
        </fileset>
    </cobertura-instrument>
    <copy todir="${cobertura.instrumented-classes.dir}">
        <fileset dir="${src.dir}" casesensitive="yes">
            <patternset id="resources.ps" />
        </fileset>
    </copy>
</target>

Add the code bellow and you will be able to execute the tests with the JUnit through the ant:

<!-- Set up the instrumented classes path -->
<path id="cover-test.classpath">
    <fileset dir="${lib.dir}" includes="**/*.jar" />
    <pathelement location="${cobertura.instrumented-classes.dir}" />
    <pathelement location="${build.dir}" />
</path>
 
<!-- Run the JUnit test -->
<target name="04-RunTest" depends="03-Instrument" >
    <junit printsummary="yes" haltonerror="no" haltonfailure="no"  fork="yes">
        <batchtest>
            <fileset dir="${build.dir}" includes="**/*Test.class" />
        </batchtest>
        <classpath refid="cover-test.classpath" />
    </junit>
    <delete file="transaction.log" />
</target>

As our last action, let us create the report using the Cobertura. Add the code bellow to your “build.xml” and execute the task:

<!-- Creates the Cobertura report -->
<target name="00-CreateReport" depends="04-RunTest">
    <cobertura-report srcdir="${cobertura.data.file}" destdir="${report.dir}">
        <fileset dir="${src.dir}">
            <include name="**/*.java" />
        </fileset>
    </cobertura-report>
 
    <delete dir="${report.dir}/instrumented-classes" />
    <delete file="cobertura.ser"  />
</target>

Update your Eclipse project (press F5 in the project) and you will see that the reports were created with success. Open the “index.html” file that it is inside the “cobertura” folder.

The Cobertura framework helps us calculating how many times we should test a method. As homework write the Dog equals method, create the report so you may see that your equals is not covered. Create your tests and run the report again.

You can download the source code from our project in here.

If you have any doubts or questions, just write it bellow.

See you soon. \o_

Reference: Covering your tests with Cobertura, JUnit, HSQLDB, JPA from our JCG partner Hebert Coelho at the uaiHebert blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


+ nine = 14



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books