Blog
navigate_next
Java
Code Coverage Tools in Java Spring Boot: A Comprehensive Guide
Shardul Lavekar
January 29, 2024

In the evolving landscape of Java application development, particularly with Spring Boot, the importance of maintaining high-quality code cannot be overstated. A key aspect in achieving this is through effective code coverage. This comprehensive guide will delve into the why and how of code coverage in Java Spring Boot, including practical setups for popular tools, and a comparative analysis to help you choose the right tool for your needs.

The Importance of Code Coverage

Code coverage is a metric used to measure the percentage of source code executed by automated tests. It plays a critical role in software development for several reasons:

  1. Quality Assurance: It helps ensure that most, if not all, code paths are tested, reducing the likelihood of bugs.
  2. Refactoring Confidence: High coverage provides a safety net for refactoring.
  3. Better Design: It encourages developers to write more testable and modular code.
  4. Risk Mitigation: Coverage metrics can identify critical untested code, highlighting potential risks.

A Simple Java Spring Boot Code Snippet

Let's consider a basic <span class="pink">Calculator</span> class in Java Spring Boot:


public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }
}

Unit Testing the Code Snippet

To ensure our <span class="pink">Calculator</span> works as expected, we write JUnit tests:


import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class CalculatorTest {

    private final Calculator calculator = new Calculator();

    @Test
    void testAdd() {
        assertEquals(5, calculator.add(2, 3));
    }

    @Test
    void testSubtract() {
        assertEquals(1, calculator.subtract(3, 2));
    }
}

Setting up the Unlogged IDE plugin for visual code coverage

Let's use the open source Unlogged IDE plugin to see how it makes unit testing easier. With the Unlogged plugin, you can:

  • Generate JUnit tests on the fly.
  • Inject mocks into code during runtime and replay the methods with mocks enabled.
  • Track code coverage visually, in real-time.

To set up the plugin in the IntelliJ IDEA, go to File → Settings or IntelliJ IDEA → Settings on macOS.

Select Plugins, and search for "Unlogged".

Click Install. Once installed, the plugin will show an "Installed" status.

We need to add some new dependencies and a plugin item to our <span class="teal">pom.xml</span> file.

Add these dependencies in the <span class="pink"><dependencies></span> tag:


<dependency>
  <artifactId>unlogged-sdk</artifactId>
  <groupId>video.bug</groupId>
  <version>0.1.45</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.16.0</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.16.0</version>
</dependency>

Run the Maven dependency resolve command to download the Unlogged dependencies and plugin:


mvn dependency:resolve

You should see the <span class="teal">BUILD SUCCESS</span>result:

Finally, reload the project using the Maven plugin. Click the Maven icon on the right side of the IntelliJ IDEA window, then select the refresh icon.

Setting Up Code Coverage Tools

1. JaCoCo

Maven: Add the following to your <span class="pink">pom.xml</span>:


<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.9</version>
    <executions>
        <execution>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <!-- other configurations -->
    </executions>
</plugin>

Gradle:

Include in your <span class="pink">build.gradle</span>:


plugins {
    id 'java'
    id 'jacoco'
}
jacoco {
    toolVersion = "0.8.9"
}

2.Cobertura

Maven:

Insert into <span class="pink">pom.xml</span>, use with JDK 8:


<reporting>
	<plugins>
		<plugin>
    	<groupId>org.codehaus.mojo</groupId>
    	<artifactId>cobertura-maven-plugin</artifactId>
    	<version>2.7</version>
    	<!-- configurations -->
		</plugin>
	</plugins>
</reporting>

3. Clover

Maven:

Add in <span class="pink">settings.xml</span> in .m2:


<pluginGroups>
    <pluginGroup>org.openclover</pluginGroup>
</pluginGroups>

or


<pluginGroups>
    <pluginGroup>com.atlassian.maven.plugins</pluginGroup>
</pluginGroups>

Note : <span class="pink">com.atlassian.maven.plugins</span> gives you access to Atlassian’s plugin which is now open source.

Generating Code Coverage Reports

JaCoCo:

Maven: Run <span class="pink">mvn test jacoco:report</span>

Gradle: Run <span class="teal">./gradlew test jacocoTestReport</span>

Cobertura:

Maven: Run <span class="pink"mvn cobertura:cobertura</span>

Clover:

Maven: Run <span class="pink">mvn clover:setup test clover:aggregate clover:clover</span>

Unlogged:

Maven: Run <span class="pink">mvn test</span>

Gradle: Run <span class="teal">./gradlew test</span>

We couldn't get Cobertura and Clover work with Gradle 8.5. Hence, we marked it as moderately hard to use.
Here is how you can track code coverage visually ⬆️

Code coverage is an indispensable tool in the Java Spring Boot developer's arsenal. Tools like Unlogged, JaCoCo, Cobertura, and Clover not only help in maintaining high-quality code but also encourage best practices in software development. By integrating these into your development workflow, you ensure robust, reliable, and maintainable Java Spring Boot applications.

Remember, while striving for high code coverage is important, the ultimate goal is to write effective tests that genuinely enhance the quality and reliability of your software.

Shardul Lavekar
January 29, 2024
Use Unlogged to
mock instantly
record and replay methods
mock instantly
Download Plugin