Add JaCoCo to Spring Boot Project

SABBAR El Mehdi
2 min readJul 10, 2021

--

https://unsplash.com

Unit testing is one of the most important parts of a project, where you test all the pieces of code and all cases for each method, and maybe one method will need dozens of tests.

If you have a very small project, you will estimate how much your tests covered your code, but what if you have a big project with hundreds and thousands of methods!

This is where you will need JaCoCo (Java Code Coverage) Library.

In the next lines, you will know how to set up JaCoCo.

Step 1: Add Plugins

<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.6</version>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<output>file</output>
<append>true</append>
<excludes>
<exclude>*MethodAccess</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<phase>test-compile</phase>
</execution>
<execution>
<id>jacoco-site</id>
<phase>verify</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>

If you use JUnit 5 you will need to add a surefire plugin too.

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
</plugin>

Step 2: Build project

Build the project and an HTML file will be generated in

~/target/site/jacoco/index.html

Step 3: Open the file

Open the file in a browser, and it will be something like this:

Source: https://www.jacoco.org/jacoco/trunk/coverage

Just make sure you have the latest version of JaCoCo, you can find the newest version here.

--

--