Code coverage with JaCoCo Maven Plugin

Code coverage is a measure of how many lines of our code are covered by the Unit Test. This is very helpful, so we can evaluate the quality of our code, how many of our code has been and have not been covered by the Unit Test. In this tutorial, I introduce to you all an Apache Maven plugin called JaCoCo Maven Plugin that helps us to measure the code coverage.

I will create a new Maven project with a simple example with Unit Test as follows:

Code coverage with JaCoCo Maven Plugin

JUnit dependency is as follows:

Calculation class:

CalculationTest class:

JaCoCo Maven Plugin:

OK, let’s get started.

JaCoCo Maven Plugin defines a lot of goals, but there is a goal that we need to declare so that the plugin can calculate the code coverage for us, that’s goal: prepare-agent. Suppose, I now declare this goal in the example project above:

then right-click on the project, select Run As, and select Maven test, then you’ll see the results in the Eclipse Console tab as follows:

As you can see in the line:

a file named jacoco.exec was created in the target directory of the project. This is the file containing the code coverage report which JaCoCo Maven Plugin created. This file is in binary format so we can not see it directly, but we still have another way to view this report result using the goal report of JaCoCo Maven Plugin.

Let’s run the Maven project with the goal jacoco:report to see how the results:

Code coverage with JaCoCo Maven Plugin

At this point, if you check the target directory for the project, you will see a directory named site containing the code coverage information that JaCoCo Maven Plugin created after we run the project with goal report:

Code coverage with JaCoCo Maven Plugin

Open the index.html file in the target/site/jacoco directory and you will see the following output:

Code coverage with JaCoCo Maven Plugin

This is all information about code coverage in our project. Can you easily see how much code coverage for each package in our project?

You can click on each package to see details:

Code coverage with JaCoCo Maven Plugin

As you can see, we can see code coverage details for each method. You can also click on each method to see what code we have covered.

Code coverage with JaCoCo Maven Plugin

By default, the code that is covered will be high light by green, and vice versa will be red. So if I now modify the code of the CalculationTest, remove:

in the testSub() method, you will see code coverage report for class Calculation now as follows:

Code coverage with JaCoCo Maven Plugin

Add Comment