0
0
JUnittesting~5 mins

JaCoCo setup and configuration in JUnit

Choose your learning style9 modes available
Introduction

JaCoCo helps you see how much of your code is tested. It shows which parts are covered by tests and which are not.

You want to check if your unit tests cover all important code parts.
You need to find untested code before releasing your software.
You want to improve your tests by adding coverage reports.
You want to integrate code coverage in your build process.
You want to share coverage reports with your team.
Syntax
JUnit
plugins {
    id 'java'
    id 'jacoco'
}

jacoco {
    toolVersion = '0.8.10'
}

test {
    useJUnitPlatform()
    finalizedBy jacocoTestReport
}

jacocoTestReport {
    dependsOn test
    reports {
        xml.required.set(true)
        html.required.set(true)
    }
}

This example is for a Gradle build file (build.gradle).

Make sure to use the correct JaCoCo version compatible with your setup.

Examples
Basic plugin setup with JaCoCo version specified.
JUnit
plugins {
    id 'java'
    id 'jacoco'
}

jacoco {
    toolVersion = '0.8.10'
}
Configure tests to run with JUnit and generate coverage report after tests.
JUnit
test {
    useJUnitPlatform()
    finalizedBy jacocoTestReport
}
Set up JaCoCo to create XML and HTML coverage reports.
JUnit
jacocoTestReport {
    dependsOn test
    reports {
        xml.required.set(true)
        html.required.set(true)
    }
}
Sample Program

This Gradle build file sets up JaCoCo with JUnit tests. The CalculatorTest checks the add method. After tests run, JaCoCo creates coverage reports in XML and HTML formats.

JUnit
plugins {
    id 'java'
    id 'jacoco'
}

jacoco {
    toolVersion = '0.8.10'
}

test {
    useJUnitPlatform()
    finalizedBy jacocoTestReport
}

jacocoTestReport {
    dependsOn test
    reports {
        xml.required.set(true)
        html.required.set(true)
    }
}

// Sample JUnit test class

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

public class CalculatorTest {
    @Test
    void testAdd() {
        Calculator calc = new Calculator();
        assertEquals(5, calc.add(2, 3));
    }
}

// Calculator class

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

Run the Gradle command ./gradlew test jacocoTestReport to execute tests and generate reports.

Check the HTML report in build/reports/jacoco/test/html/index.html to see coverage visually.

Keep your JaCoCo version updated for best compatibility and features.

Summary

JaCoCo shows which code your tests cover.

Set it up in your build tool to generate reports automatically.

Use reports to improve your tests and code quality.