Skip to content
javahacks.dev
JUnit

How to Generate Test Reports and Coverage With JaCoCo

Add JaCoCo to a Maven project to measure line and branch coverage from JUnit, produce HTML and XML reports, and enforce a minimum in the build.

5 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the JUnit5, Docker, Selenium and GitHub Actions logos.

JaCoCo measures which bytecode ran during tests. It is the standard coverage tool for Java and works with JUnit through a Java agent. This uses JaCoCo 0.8.13 or later, Maven and JDK 25. Check the plugin version supports your JDK, since coverage tools must understand each new class file version.

Maven setup

XML
<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.13</version>
  <executions>
    <execution>
      <goals><goal>prepare-agent</goal></goals>
    </execution>
    <execution>
      <id>report</id>
      <phase>verify</phase>
      <goals><goal>report</goal></goals>
    </execution>
    <execution>
      <id>check</id>
      <phase>verify</phase>
      <goals><goal>check</goal></goals>
      <configuration>
        <rules>
          <rule>
            <element>BUNDLE</element>
            <limits>
              <limit>
                <counter>BRANCH</counter>
                <value>COVEREDRATIO</value>
                <minimum>0.70</minimum>
              </limit>
            </limits>
          </rule>
        </rules>
      </configuration>
    </execution>
  </executions>
</plugin>

Run it:

Shell
./mvnw verify
open target/site/jacoco/index.html

prepare-agent sets the argLine property for Surefire, so tests run with the agent. If your Surefire configuration defines its own argLine, include @{argLine} so the agent flag is not overwritten. A report that is empty is almost always this mistake.

Reading the report

The HTML report goes from packages down to classes and source lines, with green for covered, yellow for partly covered branches and red for missed lines. The XML at target/site/jacoco/jacoco.xml is what SonarQube, Codecov and other tools read.

CounterCounts
LineSource lines with executed code
BranchBoth sides of each if and switch
InstructionBytecode instructions
ComplexityPaths in the code

A method with one if can show 100% line coverage and 50% branch coverage, if tests only take one side. That is why the rule above uses BRANCH.

Integration tests

Unit tests run by Surefire, integration tests by Failsafe. To include both, make prepare-agent-integration run too and merge the data files, or use a single jacoco.exec path. See running with Surefire and Failsafe.

Exclusions

Generated code distorts the numbers. Exclude it:

XML
<configuration>
  <excludes>
    <exclude>**/generated/**</exclude>
    <exclude>**/*Dto.class</exclude>
  </excludes>
</configuration>

JaCoCo also skips methods marked with an annotation whose simple name contains Generated and that has class or runtime retention, which Lombok and records can use.

What coverage means

A line that executes is not a line that is verified. A test with no assertions gives full coverage and no protection. Use the number as a way to find untested code, not as a target to maximise. A threshold on new code is more useful than one on the whole bundle. Good tests are discussed in the testing strategy, and the plugin setup sits alongside Surefire configuration and test parallelism.

The argLine trap

The most common reason JaCoCo reports 0 percent is that the agent never started. prepare-agent sets a property named argLine that Surefire passes to the forked test JVM. If your POM or a parent also defines <argLine> in the Surefire configuration, it replaces the property, and the agent is silently dropped. The fix is to include the property in your own value, written as @{argLine} so that it is resolved late: <argLine>@{argLine} -Xmx1g</argLine>. If coverage is empty, run mvn -X test and search for -javaagent in the forked command line. Its absence confirms the cause in a minute.

The second cause is a JaCoCo version older than your JDK. The tool reads bytecode, and a version that does not know the class file format fails with Unsupported class file major version. Use a release that supports the JDK you build with, and bump it when you upgrade Java.

Thresholds that do not backfire

A check goal can fail the build below a coverage threshold. Set it on the whole project and ratchet it: write down the current number, set the rule slightly below it, and raise it when coverage improves. A threshold of 80 percent chosen from a book produces tests that call methods and assert nothing, because that is the cheapest way to turn a number green. Prefer a rule on changed code in the pull request, which tools such as Sonar or Codecov report, so the standard applies to new work and does not punish old code. Branch coverage says more than line coverage, since an if with only one side exercised still counts as a covered line.

Generated code and Lombok

Generated classes and Lombok output inflate or distort the numbers. Exclude generated packages in the plugin configuration, and if you use Lombok, add lombok.addLombokGeneratedAnnotation = true to lombok.config, which marks generated methods so that JaCoCo ignores them. Excluding hand-written code you dislike testing is the opposite, and the number stops meaning anything.

Beyond coverage

Coverage tells you what code ran, and not whether the tests would notice a bug. A mutation testing tool such as PIT changes the code in small ways, and checks that a test fails each time. It is slow, so run it on the modules that matter, or only on changed classes. A project with 90 percent line coverage and a 40 percent mutation score has tests that execute code without checking it, and the second number is the one to improve.

Merging coverage from several modules

A multi-module build produces a report per module, and the number that matters is for the whole application. The report-aggregate goal, run in a dedicated module that depends on the others, merges them into one report. Make sure each module writes its jacoco.exec file, and that the aggregate module lists the modules to include. For integration tests that run in a separate phase or against a deployed application, attach the agent to that process and merge the execution data afterwards with the merge goal. Coverage of unit tests alone understates what the system exercises, and coverage of integration tests alone hides untested branches.

Publishing the results

Publish the XML report to a service such as SonarQube or Codecov, and let pull requests show the change in coverage and the coverage of the changed lines. Keep the HTML report as a build artifact, so a developer can open it and see which lines are red without running anything locally. A report that nobody opens is a number on a badge, and an HTML report one click away turns coverage into a tool for finding the untested branch in the code you just wrote.

Reading the report in practice

Open the package view first and sort by missed branches, because the biggest gaps sit in a handful of classes. Click into a class, and the red and yellow lines are the cases no test reached.

Where this does not apply

Coverage cannot see behaviour that runs in another process or a container started by the test. The official JaCoCo Maven plugin documentation lists the parameters, and the counters page defines each measure.

Also inDevOps
Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.