JaCoCo for Java and Spring Boot: Coverage Reporting That Actually Works

JaCoCo for Java and Spring Boot: Coverage Reporting That Actually Works

JaCoCo is the de facto standard for Java code coverage. It instruments bytecode at runtime using a Java agent, which means it works regardless of how your code was compiled and doesn't require source-level transformation. For Spring Boot projects specifically, there are enough quirks — generated proxies, Lombok annotations, JPA entities — that a naive configuration produces misleading numbers.

This guide covers the full setup for real projects.

Maven Setup

Add the JaCoCo plugin to your pom.xml:

<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.11</version>
  <executions>
    <execution>
      <id>prepare-agent</id>
      <goals>
        <goal>prepare-agent</goal>
      </goals>
    </execution>
    <execution>
      <id>report</id>
      <phase>test</phase>
      <goals>
        <goal>report</goal>
      </goals>
    </execution>
    <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.75</minimum>
              </limit>
            </limits>
          </rule>
        </rules>
      </configuration>
    </execution>
  </executions>
</plugin>

The prepare-agent goal sets up the JaCoCo agent before tests run. Without it, no coverage data is collected. The report goal generates the HTML/XML report after tests complete. The check goal enforces thresholds and fails the build if they're not met.

Run with:

mvn clean verify

The report appears in target/site/jacoco/.

Gradle Setup

plugins {
    id 'jacoco'
}

jacoco {
    toolVersion = "0.8.11"
}

test {
    finalizedBy jacocoTestReport
}

jacocoTestReport {
    dependsOn test
    reports {
        xml.required = true
        html.required = true
    }
}

jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                counter = 'LINE'
                value = 'COVEREDRATIO'
                minimum = 0.80
            }
            limit {
                counter = 'BRANCH'
                value = 'COVEREDRATIO'
                minimum = 0.75
            }
        }
    }
}

check.dependsOn jacocoTestCoverageVerification

For Kotlin DSL (build.gradle.kts):

plugins {
    jacoco
}

tasks.test {
    finalizedBy(tasks.jacocoTestReport)
}

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

tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                counter = "BRANCH"
                value = "COVEREDRATIO"
                minimum = "0.75".toBigDecimal()
            }
        }
    }
}

tasks.check {
    dependsOn(tasks.jacocoTestCoverageVerification)
}

Report Types

JaCoCo generates several report formats, each useful for different purposes:

HTML: Human-readable, drill-down from package to class to method to line. This is what you open when coverage drops and you need to understand what's missing.

XML: Machine-readable, consumed by CI integrations (SonarQube, Codecov, Jenkins). Always generate this in CI.

CSV: Useful for scripting — you can parse it to extract coverage by package and build custom reports or alerts.

Exec: The raw binary data file (jacoco.exec). All other formats are generated from this. If you're running tests in multiple JVMs (e.g., integration tests in a separate profile), you can merge exec files:

mvn jacoco:merge

Branch Coverage in JaCoCo

JaCoCo's branch coverage tracks every conditional branch in your bytecode. This includes:

  • if/else statements
  • Ternary expressions
  • switch statements
  • Boolean short-circuit evaluation (&&, ||)
  • Exception handling paths

The HTML report shows branch coverage with diamond markers in the gutter: green diamond means all branches covered, yellow means partial, red means uncovered.

A critical distinction: JaCoCo counts bytecode branches, not source branches. This means Kotlin's when expressions, Lombok-generated equals()/hashCode() methods, and compiler-generated null checks all produce branches in the bytecode that your source-level test cases may not be targeting.

Spring Boot Test Slices

Spring Boot's @SpringBootTest loads the full application context, which is slow. Test slices (@WebMvcTest, @DataJpaTest, @JsonTest) load only a subset of the context.

The coverage problem: JaCoCo uses a single agent across the JVM process. Tests run in separate Spring contexts don't automatically merge their coverage data unless you configure it.

For Maven, coverage from multiple test executions merges automatically if they all write to the same jacoco.exec file. For separate integration test phases, use the destFile and append configuration:

<execution>
  <id>prepare-agent-integration</id>
  <phase>pre-integration-test</phase>
  <goals>
    <goal>prepare-agent-integration</goal>
  </goals>
  <configuration>
    <destFile>${project.build.directory}/jacoco-it.exec</destFile>
  </configuration>
</execution>
<execution>
  <id>merge-results</id>
  <phase>verify</phase>
  <goals>
    <goal>merge</goal>
  </goals>
  <configuration>
    <fileSets>
      <fileSet>
        <directory>${project.build.directory}</directory>
        <includes>
          <include>*.exec</include>
        </includes>
      </fileSet>
    </fileSets>
    <destFile>${project.build.directory}/jacoco-merged.exec</destFile>
  </configuration>
</execution>

Excluding Generated Code

Spring Boot projects accumulate significant amounts of code you didn't write and shouldn't be held responsible for covering: Lombok-generated methods, JPA metamodel classes, generated MapStruct mappers, Spring-generated configuration classes.

Configure exclusions in the report goal:

<configuration>
  <excludes>
    <exclude>**/generated/**</exclude>
    <exclude>**/*MapperImpl.class</exclude>
    <exclude>**/*_.class</exclude>
    <exclude>**/config/SecurityConfig.class</exclude>
    <exclude>com/example/Application.class</exclude>
  </excludes>
</configuration>

For Gradle:

jacocoTestReport {
    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it, exclude: [
                '**/generated/**',
                '**/*MapperImpl.class',
                '**/*_.class',
                '**/Application.class'
            ])
        }))
    }
}

The same exclusions need to apply to both the report goal and the check goal, or your thresholds will be measured against different sets of classes than what's in the report.

For Lombok specifically, create a lombok.config file in your project root:

lombok.addLombokGeneratedAnnotation = true

This adds @lombok.Generated to all Lombok-generated methods. JaCoCo 0.8.2+ automatically excludes classes and methods annotated with @Generated, which means Lombok getters, setters, builders, and equals()/hashCode() implementations are excluded automatically.

Per-Class Coverage Rules

The BUNDLE element in the check configuration sets rules for the entire project. For more granular control, use CLASS or PACKAGE level rules:

<rules>
  <rule>
    <element>CLASS</element>
    <excludes>
      <exclude>*Test</exclude>
      <exclude>*Config</exclude>
    </excludes>
    <limits>
      <limit>
        <counter>LINE</counter>
        <value>COVEREDRATIO</value>
        <minimum>0.70</minimum>
      </limit>
    </limits>
  </rule>
  <rule>
    <element>PACKAGE</element>
    <includes>
      <include>com/example/payments/**</include>
    </includes>
    <limits>
      <limit>
        <counter>BRANCH</counter>
        <value>COVEREDRATIO</value>
        <minimum>0.90</minimum>
      </limit>
    </limits>
  </rule>
</rules>

CI Integration

GitHub Actions setup for Maven:

name: Build and Test

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'
          cache: maven

      - name: Run tests with coverage
        run: mvn clean verify

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v3
        with:
          files: target/site/jacoco/jacoco.xml
          fail_ci_if_error: true

      - name: Upload JaCoCo report
        uses: actions/upload-artifact@v3
        if: always()
        with:
          name: jacoco-report
          path: target/site/jacoco/

For SonarQube integration, the XML report path needs to be specified:

- name: SonarQube analysis
  run: mvn sonar:sonar
    -Dsonar.projectKey=my-project
    -Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml
  env:
    SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
    SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}

What the Numbers Mean

JaCoCo's instruction coverage (C0) counts individual bytecode instructions. Line coverage (C1) counts executed source lines. Branch coverage (C2) counts decision branches.

For Spring Boot services, a realistic baseline is:

  • 80% line coverage is achievable with unit + slice tests
  • 70% branch coverage requires deliberate testing of error paths and conditional logic
  • 95%+ line coverage usually means you're either testing trivial code or have unrealistic exclusions

The most useful thing JaCoCo tells you isn't the global percentage — it's the uncovered branches in your service layer and domain logic. Those are where bugs live. Everything else is bookkeeping.

Read more

Start now free