JaCoCo Code Coverage: Prove Your Tests Actually Run the Code

Friday, 3 PM. The checkout team's CI is green — 214 tests, all passing — and the new discount engine ships. Saturday, 9 AM: support tickets. A leaked promo code for 60% off is sailing straight through the "maximum 50% discount" guard that was the whole point of the release. The fix is a one-line change. The uncomfortable question in the postmortem is harder: how did 214 passing tests miss it?

The answer, when someone finally looked, was embarrassing in the way only obvious things can be. The guard clause was fine. The logic was fine. No test had ever executed the guard. The suite tested discounts of 10%, 20%, 25% — never a rate the guard was supposed to reject. Every test passed because none of them went near the new code.

Code coverage is the tool that answers the question nobody asked that Friday: how much of my code do my tests actually run? Not "do the tests pass" — "which lines, which branches, have they ever touched." This post wires JaCoCo — the Java Code Coverage library, the standard for Maven and Gradle builds — into a real project, reads a real report, and turns it into a build gate that would have stopped that release.

What coverage actually measures

JaCoCo doesn't read your source. It instruments your bytecode — inserts tiny probes at every line and branch — runs your tests, and counts which probes fired. It reports three counters you'll see everywhere:

  • Line coverage — did execution reach this line at least once? The bluntest number.
  • Branch coverage — for every if, loop, and boolean operator, did execution take both paths? Reaching a line is not the same as testing its decisions: an if (rate < 0 || rate > 0.5) has four edges, and a test that only ever evaluates them false has left half the decision unexamined.
  • Method coverage — was the method entered at all? Useful for spotting dead code and untested helpers.

The ratio that matters most is usually branch coverage. Line coverage is easy to game — one happy-path test can touch every line of a method while leaving every guard clause half-tested. Branch coverage is the one that would have flagged our discount guard.

The example: a discount calculator

Here is the entire class, small enough to reason about completely. It lives in the checkout service's billing package — the same codebase this track has been building with since the Maven post:

package com.javamakeuse.billing;

public class DiscountCalculator {
    public double apply(double price, double discountRate) {
        if (price < 0) {
            throw new IllegalArgumentException("price must be >= 0");
        }
        if (discountRate < 0 || discountRate > 0.5) {
            throw new IllegalArgumentException("discountRate must be in [0, 0.5]");
        }
        return price * (1 - discountRate);
    }
}

And here is the test suite as it shipped that Friday — one test, written against the happy path, in the JUnit 5 style from this track's JUnit 5 & Mockito post:

package com.javamakeuse.billing;

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

class DiscountCalculatorTest {
    private final DiscountCalculator calc = new DiscountCalculator();

    @Test
    void tenPercentOffHundred() {
        assertEquals(90.0, calc.apply(100.0, 0.10), 0.0001);
    }
}

One test, one assertion, green bar. Now let's ask the question coverage asks.

Wiring JaCoCo into Maven

JaCoCo is a Maven plugin with three jobs, bound to three build phases. prepare-agent attaches the instrumentation agent before tests run. report turns the raw execution data into the HTML/XML reports after tests finish. (check — the build gate — comes later in this post.)

<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.15</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>
  </executions>
</plugin>

(Check for newer artifact versions than the one pinned above — the coordinates are the stable part. 0.8.15 officially supports Java 25.) Then run:

mvn test

The agent records every probe hit into target/jacoco.exec while Surefire runs your tests; the report goal converts it into target/site/jacoco/index.html. Open that file in a browser.

Gradle users: apply the built-in jacoco plugin (plugins { id 'jacoco' }), set jacoco { toolVersion = "0.8.15" }, and run ./gradlew test jacocoTestReport. The same report lands in build/reports/jacoco/test/html/index.html.

source bytecode + probes mvn test probes fire jacoco.exec raw hit data report target/site/jacoco/ check (the gate) ratios vs. minimums build passes ratios above minimums build fails coverage dropped instrument → run tests → record → report → enforce

Reading the report: our example, honestly counted

With only tenPercentOffHundred in the suite, the report for DiscountCalculator.apply looks like this (counters as JaCoCo actually computes them from the bytecode — you can verify the arithmetic against the class above):

Element                Missed Lines   Line %    Missed Branches   Branch %
DiscountCalculator            2        60%               3          50%
  apply(double, double)       2        60%               3          50%

Where those numbers come from:

  • Lines: 3 of 5 covered (60%). The test executes the two if conditions and the return — but never executes either throw line.
  • Branches: 3 of 6 covered (50%). The price guard contributes 2 branches (taken / not taken); only "not taken" fired. The rate guard discountRate < 0 || discountRate > 0.5 contributes 4 — one per edge of the || — and the test only ever evaluated both operands false. The two "throw" edges never fired.

The report also highlights the exact missed lines in red in the HTML view — click through to the source page and the two throw lines glow. That red is the whole point: coverage doesn't tell you your code is correct, it tells you where you haven't looked.

if (price < 0) { COVERED throw new IllegalArgumentException("price must be >= 0"); MISSED if (discountRate < 0 || discountRate > 0.5) { COVERED throw new IllegalArgumentException("discountRate must be in [0, 0.5]"); MISSED return price * (1 - discountRate); COVERED 60% lines · 50% branches — the red lines are exactly where the 60%-off promo code slipped through

The coverage gate: failing the build on purpose

A report nobody is forced to read is a dashboard nobody opens. The check goal turns coverage into a rule: if the ratios fall below your minimums, mvn verify fails. This is the rule that would have stopped the Friday release — the new guard clause arrived with zero tests, and the gate would have said so.

<execution>
  <id>check</id>
  <phase>verify</phase>
  <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>

Two honest choices here. 0.80 line / 0.70 branch is a sane starting point for a real codebase — strict enough to catch "shipped untested code," lenient enough that one generated DTO doesn't red-light the whole build. Gate on the trend, not an absolute: on legacy code, set the minimums at today's ratios and forbid decreases. A gate that demands 80% on a codebase sitting at 40% just teaches everyone to disable the gate.

Wire it into the pipeline from this track's CI/CD with GitHub Actions post — the only change is running verify (which includes the check goal) instead of bare test:

- name: Build, test and enforce coverage gate
  run: mvn -B verify

If coverage falls below the minimums, this step fails and the PR can't merge. The gate is now part of the definition of "green."

Closing the gaps

The report told us exactly what to write. Two tests cover the missed lines; the third input covers the last untested edge of the ||:

@Test
void rejectsBadInputs() {
    assertThrows(IllegalArgumentException.class, () -> calc.apply(-1.0, 0.10));
    assertThrows(IllegalArgumentException.class, () -> calc.apply(100.0, 0.75));
    assertThrows(IllegalArgumentException.class, () -> calc.apply(100.0, -0.10));
}

Run mvn verify again: lines 5/5 (100%), branches 6/6 (100%). The gate passes. Notice what happened here — coverage didn't tell us what to assert. It pointed at the red lines and said "write a test that goes here." The thinking was still ours. That's the honest contract: coverage finds the untested code; you still have to test it well.

What coverage does NOT prove

Here is the part most coverage tutorials skip, and it's the most important section of this post. Add this test to the suite:

@Test
void discountDoesNotThrow() {
    calc.apply(100.0, 0.10);   // passes — and proves nothing
}

This test has no assertion. It calls the method, ignores the result, and passes. And JaCoCo loves it: it fires every probe, keeps both ratios at 100%, and the gate stays green. Coverage measures execution, not verification. A suite of assert-less tests is a green build wrapped around untested behavior.

Three more honest limits:

  • Covered line ≠ correct behavior. Change price * (1 - discountRate) to price * (1 + discountRate) — a one-character class of bug — and every line and branch is still "covered." The report stays green while the math is backwards.
  • Branch subtleties. discountRate > 0.5 vs discountRate >= 0.5 — the boundary the fraud rule actually cares about — is invisible to coverage. Both versions execute identically on every test that doesn't probe exactly 0.5.
  • 100% is a vanity number on the wrong code. Generated code, trivial getters, and toString methods inflate the ratio. Exclude what shouldn't be gated (<excludes> in the plugin config) and read the report per-package, not just the headline number.

Decision rules: treat coverage as a floor, never a proof. A dropping ratio is a signal — investigate the PR. A green ratio is permission to ask the harder question, not an answer to it. And never let anyone merge an assert-less test just because it "keeps coverage green" — that's the suite lying to you with JaCoCo's help.

What's next

Coverage answers "does the code run." The harder question — "does the test actually catch bugs?" — needs a tool that fights back: mutation testing. The next post in this track takes the same DiscountCalculator, seeds tiny bugs into it, and checks whether your tests notice. The assert-less test above is the star of that show.

Field check before you move on: add the JaCoCo plugin to any project you own, run mvn test, and open the HTML report. Find the reddest class. Write one test that turns one red line green — then delete one assertion from an existing test and confirm the ratio doesn't move. That gap between "covered" and "verified" is the entire next post.

Continue: Java Learning Roadmap 2026

Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

What are the core classes and interfaces of hibernate 4

Java Banking Finance Services and Insurance (BFSI) domain interview questions