JaCoCo Java Code Coverage: Complete Setup and CI Integration Guide
JaCoCo is the standard Java code coverage library. It instruments bytecode at runtime to track which lines, branches, and methods are executed by tests. This guide covers Maven and Gradle setup, generating HTML/XML reports, enforcing minimum coverage thresholds, and integrating with SonarQube and CI pipelines.
JaCoCo (Java Code Coverage) has been the dominant Java coverage tool for over a decade. It instruments JVM bytecode using a Java agent, tracks execution during test runs, and generates reports showing which lines, branches, methods, and classes were exercised. Spring Boot projects get JaCoCo support out of the box through the Spring Boot build plugins.
How JaCoCo Works
JaCoCo uses two instrumentation modes:
- Java agent (recommended): Attaches to the JVM at startup (
-javaagent:jacocoagent.jar). Modifies classes in memory as they're loaded. No source code changes needed. - Offline instrumentation: Pre-processes class files before running tests. Used when the Java agent approach isn't feasible (Android, GraalVM).
The agent writes coverage data to a .exec file when the JVM shuts down (or when explicitly dumped). The report generator reads .exec + compiled class files + source files to produce human-readable reports.
Maven Setup
<!-- pom.xml -->
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.11</version>
<executions>
<!-- Attach agent before tests -->
<execution>
<id>prepare-agent</id>
<goals><goal>prepare-agent</goal></goals>
</execution>
<!-- Generate report after tests -->
<execution>
<id>report</id>
<phase>verify</phase>
<goals><goal>report</goal></goals>
</execution>
<!-- Enforce minimum coverage -->
<execution>
<id>check</id>
<goals><goal>check</goal></goals>
<configuration>
<rules>
<rule>
<element>BUNDLE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0.80</minimum>
</limit>
<limit>
<counter>BRANCH</counter>
<value>COVEREDRATIO</value>
<minimum>0.70</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build># Run tests and generate coverage report
mvn verify
# Report at: target/site/jacoco/index.htmlGradle Setup
// build.gradle
plugins {
id 'java'
id 'jacoco'
}
jacoco {
toolVersion = "0.8.11"
}
test {
finalizedBy jacocoTestReport // Generate report after tests
}
jacocoTestReport {
dependsOn test
reports {
xml.required = true // For CI integration (SonarQube, Codecov)
html.required = true // Human-readable
csv.required = false
}
// Exclude generated code from coverage
classDirectories.setFrom(files(classDirectories.files.collect {
fileTree(dir: it, exclude: [
"com/example/generated/**",
"com/example/config/SecurityConfig.class"
])
}))
}
jacocoTestCoverageVerification {
violationRules {
rule {
limit {
counter = 'LINE'
value = 'COVEREDRATIO'
minimum = 0.80
}
}
rule {
limit {
counter = 'BRANCH'
value = 'COVEREDRATIO'
minimum = 0.70
}
}
}
}
check.dependsOn jacocoTestCoverageVerification# Run tests with coverage
./gradlew test jacocoTestReport
# Enforce coverage threshold
./gradlew jacocoTestCoverageVerification
# Both (via check)
./gradlew checkSpring Boot Setup
Spring Boot's parent POM doesn't include JaCoCo by default. Add the plugin manually, but Spring Boot's test support integrates cleanly:
<!-- Spring Boot with JaCoCo - pom.xml -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.11</version>
<executions>
<execution>
<goals><goal>prepare-agent</goal></goals>
</execution>
<execution>
<id>report</id>
<phase>verify</phase>
<goals><goal>report</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>For Spring Boot integration tests that run a full application context:
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class OrderApiIntegrationTest {
@Autowired private TestRestTemplate restTemplate;
@Test
void createOrderReturns201() {
// JaCoCo tracks coverage through entire call stack:
// Controller → Service → Repository → Database
}
}JaCoCo instruments classes at load time. Both unit tests and integration tests contribute to the same .exec file and coverage report.
Coverage Metrics Explained
JaCoCo reports six counter types:
| Counter | What It Measures |
|---|---|
| LINE | Source code lines executed |
| BRANCH | Boolean branches taken (if/else, switch, ternary) |
| METHOD | Methods called at least once |
| CLASS | Classes instantiated or having static code executed |
| INSTRUCTION | Individual Java bytecode instructions |
| COMPLEXITY | Cyclomatic complexity of executed paths |
Line coverage is the most commonly reported metric. Branch coverage is more meaningful for catching logical errors—a line can be "covered" while only one branch of an if statement is ever executed.
Example:
public String classify(int score) {
if (score >= 90) { // Line covered
return "A"; // Branch: only taken if score >= 90
} else if (score >= 80) { // Branch: only taken if 80 <= score < 90
return "B"; // ← never tested if no test has score 80-89
} else {
return "C";
}
}A test with score = 95 gives 100% line coverage for the if block but 33% branch coverage (only one of three branches tested).
Excluding Code from Coverage
Not all code needs coverage. Exclude generated code, configuration classes, and DTOs:
Maven Exclusions
<configuration>
<excludes>
<exclude>com/example/generated/**/*.class</exclude>
<exclude>com/example/config/WebSecurityConfig.class</exclude>
<exclude>**/*DTO.class</exclude>
<exclude>**/model/**/*.class</exclude>
</excludes>
</configuration>Gradle Exclusions
jacocoTestReport {
classDirectories.setFrom(files(classDirectories.files.collect {
fileTree(dir: it, exclude: [
"**/generated/**",
"**/*DTO.class",
"**/model/**"
])
}))
}Annotation-Based Exclusion
JaCoCo respects @Generated annotations:
// Mark generated code
@javax.annotation.Generated("com.example.codegen")
public class GeneratedMapper {
// JaCoCo excludes this class from reports
}Or use Lombok's @Generated:
@lombok.Generated
public String toString() { ... }Merging Coverage from Multiple Modules
For multi-module Maven projects, generate an aggregate report:
<!-- parent/pom.xml -->
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<executions>
<execution>
<id>prepare-agent</id>
<goals><goal>prepare-agent</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<!-- report-aggregate/pom.xml (dedicated module) -->
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<executions>
<execution>
<id>report-aggregate</id>
<phase>verify</phase>
<goals><goal>report-aggregate</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>mvn verify
# Report at: report-aggregate/target/site/jacoco-aggregate/index.htmlGitHub Actions Integration
name: Build and Coverage
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
- name: Build with Maven
run: mvn verify
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v4
with:
file: target/site/jacoco/jacoco.xml
token: ${{ secrets.CODECOV_TOKEN }}
- name: Upload JaCoCo HTML report
uses: actions/upload-artifact@v4
with:
name: jacoco-report
path: target/site/jacoco/SonarQube Integration
SonarQube reads JaCoCo's XML report automatically when configured:
<!-- Maven: add SonarQube plugin -->
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.10.0.2594</version>
</plugin>mvn verify sonar:sonar \
-Dsonar.host.url=http://sonarqube.example.com \
-Dsonar.login=$SONAR_TOKEN \
-Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xmlSonarQube will fail the Quality Gate if coverage drops below configured thresholds, blocking PRs from merging.
Common Issues
Coverage Always Shows 0%
The JaCoCo agent isn't attached. Verify:
prepare-agentexecution ran beforetestphase- No
forkCount=0override that prevents agent attachment when tests run in-process
Kotlin Classes Show Low Coverage
JaCoCo doesn't handle Kotlin null-safety checks and when expressions perfectly. Use the Kotlin-specific JaCoCo configuration:
// Kotlin + Gradle
tasks.withType(KotlinCompile) {
kotlinOptions.jvmTarget = "21"
}
jacocoTestReport {
classDirectories.setFrom(files(classDirectories.files.collect {
fileTree(dir: it, exclude: ["**/*\$\$serializer.class"])
}))
}Report Missing Classes
Classes must be compiled when the report is generated. Run mvn compile test-compile verify rather than just mvn verify if some classes aren't appearing.
Summary
JaCoCo is the standard for Java coverage because it works transparently: attach the agent, run tests, get reports. For Maven projects, the prepare-agent + report + check execution lifecycle is the canonical setup. Set branch coverage thresholds alongside line coverage—branch coverage catches the logical gaps that line metrics miss. Integrate with SonarQube or Codecov for PR-level visibility and automatic quality gates in your CI pipeline.