Monthly Archives: June 2021

Measuring JUnit CodeCoverage with Jacoco

Once you start working with unit tests, and that you understand how to use and write them, it’s impossible to go back. They help you decouple code, gain confidence in the behaviour you’re implementing, makes you faster by avoiding to start, and restart, a whole application.

Yet, one thing I never used up to now was code coverage. I just never took the time to dig the topic, even though that’s clearly useful. It helps maintain a team effort to ensure all new code is tested, and it gives you an idea of the risk you’re taking when chaging a line of code. Because the number of tests doesn’t give you any idea about the coverage, they may be focused on one part of the application only, or at the opposite cover a little bit every part, but not completely.

It appeared that adding code coverage measurement to a maven Java project using JUnit was as simple as adding the JaCoCo plugin to the POM file. As usual, Baeldung is your reference, but in brief :

            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.2</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>report</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

The JaCoCo plugin will output a jacoco.exec binary file, which can be consumed by some third party tools, like SonarQube. However, you can generate a more human friendly report using the repot goal :

mvn clean jacoco:prepare-agent install jacoco:report

You’ll then have a target\site\jacoco\index.html report detailing your code coverage :