John Dobie is an independent consultant specialising in Java enterprise architecture and development. He is a certified as a Java architect, SCWCD, programmer and ScrumMaster(CSM) with over 15 years of Java experience. Most of the last 15 years has been spent in London in Finance IT working on Java trading and banking systems. Currently he specialises in leading and mentoring teams to improving their Agile engineering practices. John is a DZone MVB and is not an employee of DZone and has posted 11 posts at DZone. You can read more from them at their website. View Full User Profile

Unit Test Code Coverage

  • submit to reddit
It’s easy to collect unit test code coverage because all of the common tools are geared up for it.
This article will explain how you can add unit test coverage to your Maven application in 10 minutes.
We will use the excellent Jacoco code coverage library to show how easy it is.


All of the examples come from this article.

You can check them out from here
svn co

With Maven 3 installed, you can run them with this command.
mvn clean package

What is Jacoco

Jacoco is a free code coverage library for Java. I use it because it is very simple to add to all types of build including ANT and Maven, and it is also very simple to add to Java containers or a standalone JVM.

How Does it Work?

Jacoco uses the standard JVM Tool Interface.
In simple terms you attach a Jacoco agent to a JVM when it starts. It was introduced in JDK 5 for monitoring and profiling JVMs and being able to dynamically modify Java classes as they're being loaded.
Whenever a class is loaded Jacoco can instrument the class so it can see when the class is called and what lines are called. That’s how it builds up the coverage statistics. This is all done on the fly.
By default the results file is created when the JVM terminates. You can also run the agent in server mode which allows you to trigger a dump of the results.

Attaching the agent to the JVM?

This is a very simple process. You must specify where the jacoco jar is located and then you pass some parameters to define how the agent is to run.
A typical run might look like this
A full reference is found here.

Jacoco Support For Maven

The docs for the maven plugin are defined here.
First we need to add the plugin itself.
We can then define where the jacoco reports are output.

Finally we need to define the following 2 executions to make the agent run before the tests are run and also to make sure that the jacoco report task is run when package is executed.
The full pom.xml can be found here pom

To run the examples execute the following command.
mvn clean package 


The results are published in /target/site/jacoco.
The original article can be found here
Published at DZone with permission of John Dobie, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)