# Code Coverage with JaCoCoA green build and a hundred percent line coverage still let a bug through. Learn what JaCoCo measures, how to read its report, how to enforce a rule, and what coverage can't tell you.

Your shipping tests are green. The coverage report says every line ran, a hundred percent. The team
is proud of that number. Then a small edit changes one comparison: orders of at least a hundred
dollars used to ship free, and now an order of exactly a hundred pays for shipping. The build stays
green. Coverage stays at a hundred percent. How can a bug walk past both?

Prefer to watch? The narrated video covers the same lesson (about ten minutes). The article follows
it section by section, with diagrams, the Maven equivalent and a little extra depth.

{{< lesson-video youtube="8HAsMdv4Fnk" title="Code Coverage with JaCoCo" >}}

This is the first of two lessons on measuring your tests. Here we measure what **ran**. The next
one, [mutation testing with PIT](/testing/pit-mutation-testing/), measures what was **checked**. Both build on
[unit testing with JUnit 5](/testing/junit5-unit-testing/).

## The code under test

Everything in both lessons uses one small class. An order has a total and an express flag. The
`cost` method returns zero shipping when the total is at least 100, and the flat rate otherwise.
Express orders add 15 on top.

```java
public record Order(double total, boolean express) {}
```

```java
public double cost(Order order) {
    double shipping;
    if (order.total() >= 100) {
        shipping = 0;
    } else {
        shipping = 7.99;
    }
    if (order.express()) {
        shipping += 15;
    }
    return shipping;
}
```

That is two decisions in a few lines, so the method has real branches to cover. Here are the tests.
One calls `cost` on a big express order and never checks the result. The other only checks that
the cost is above zero.

```java
class ShippingCalculatorTest {
    private final ShippingCalculator calc = new ShippingCalculator();

    @Test
    void bigOrder() {
        calc.cost(new Order(120, true));
    }

    @Test
    void smallOrder() {
        assertTrue(calc.cost(new Order(50, true)) > 0);
    }
}
```

Both pass. Keep these two tests in mind: they are the heroes (and villains) of this lesson and the
next.

## A delivery van's GPS trace

Picture a delivery van with a GPS trace. The trace shows every street the driver drove down today.
A complete trace proves every street was visited. It doesn't prove a single parcel arrived. A driver
could even nap in the van at every corner, and the trace would still look perfect.

Coverage is that trace. Your code is the map, your tests are the drivers, and an assertion is the
signature at the door.

```mermaid {alt="The GPS-trace analogy mapped onto testing: the GPS trace is the coverage report, the map is your code, the drivers are your tests, and the signature at the door is an assertion." caption="The van, mapped onto the lesson."}
flowchart LR
  A1["GPS trace"] --> B1["coverage report"]
  A2["the map"] --> B2["your code"]
  A3["the drivers"] --> B3["your tests"]
  A4["signature at the door"] --> B4["an assertion"]
  class A1,A2,A3 c4
  class B1,B2,B3 c1
  class A4 hl
  class B4 good
```

A fully green map means nothing was skipped. It says nothing about delivery.

## What JaCoCo is, and the Gradle setup

JaCoCo is a Java agent. While your tests run, it instruments each class as it loads, so it can
record which instructions execute. When the tests finish, the agent saves what it saw into an exec
file. A second step matches that file against your compiled classes and turns it into a report.

```mermaid {alt="Coverage pipeline: tests run in a JVM with the JaCoCo agent, which writes exec data; the report step combines the exec data with the compiled classes; an optional check step applies a rule to the result." caption="From test run to rule."}
flowchart LR
  T["tests run<br/>with the agent"] --> E["exec data"]
  E --> R["report"]
  C["compiled<br/>classes"] --> R
  R --> K["check<br/>(a rule)"]
  class T c5
  class E,C c1
  class R good
  class K hl
```

In Gradle, apply the `jacoco` plugin. The test task already uses the JUnit platform, so JUnit 5
tests run. Then tell it to be finalized by the report task.

```kotlin
plugins {
    java
    jacoco
}

tasks.test {
    useJUnitPlatform()
    finalizedBy(tasks.jacocoTestReport)
}
```

Now `gradle test` runs your tests, and the report follows. Without the `finalizedBy` line the report
task doesn't depend on `test` by default, so it never runs unless you ask for it. The HTML report
lands in `build/reports/jacoco/test/html`.

A complete `build.gradle.kts` for the example project, with the JUnit 5 dependencies:

```kotlin
plugins {
    java
    jacoco
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(platform("org.junit:junit-bom:5.14.4"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test {
    useJUnitPlatform()
    finalizedBy(tasks.jacocoTestReport)
}
```

The same setup in **Maven** uses the plugin's `prepare-agent` goal (it sets the `argLine` that
Surefire passes to the test JVM) and the `report` goal:

```xml
<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.16</version>
  <executions>
    <execution>
      <goals>
        <goal>prepare-agent</goal>
      </goals>
    </execution>
    <execution>
      <id>report</id>
      <goals>
        <goal>report</goal>
      </goals>
    </execution>
  </executions>
</plugin>
```

By default `prepare-agent` runs in the `initialize` phase and `report` in `verify`, so
`mvn verify` runs the tests and then writes `target/site/jacoco/index.html`.

## Reading the report

Open the HTML report, and open the `cost` method. Every line gets a coloured background. Green means
every instruction on the line ran. Red means none of them did, and yellow means some did.

Lines with a decision also get a diamond in the margin. A green diamond means every branch was
taken. A yellow diamond means only some were.

Look at the express line. The line itself is green, but its diamond is yellow. One way out of that
decision, the not-express branch, never ran, and a line colour alone would never have told us.

```mermaid {alt="The cost method as a flow: the first decision, total at least 100, has both of its branches taken; the second decision, express, has only its yes branch taken, and the skip-the-fee branch is never taken." caption="The express decision: one way out never ran."}
flowchart TD
  S["cost(order)"] --> A{"total at least 100?"}
  A -->|yes| A1["shipping = 0"]
  A -->|no| A2["shipping = 7.99"]
  A1 --> B{"express?"}
  A2 --> B
  B -->|yes| B1["shipping += 15"]
  B -->|no| B2["skip the fee"]
  B1 --> R["return shipping"]
  B2 --> R
  class A1,A2,B1 good
  class B2 bad
```

Red lines are the most useful part of the report. They point at code that no test ever reached.
(The report in the video is a stylised drawing in the same colours, not a screenshot.)

## The six counters

The summary table shows six counters:

| Counter | What it counts |
|---|---|
| Instructions | each bytecode instruction that ran or didn't |
| Lines | a source line counts as run when any of its instructions ran (needs debug information) |
| Branches | the ways out of every `if` and `switch`; exception handling isn't counted |
| Methods | a method counts as run when one of its instructions ran |
| Classes | a class counts as run when one of its methods ran |
| Complexity | the minimum number of paths that combine to cover every path through a method |

For your tests, two counters matter most. Lines show what ran. Branches show which choices ran.

## Line versus branch

Here is our calculator with the two tests we started with. Six lines hold code, and the tests run all
six, so line coverage is a hundred percent.

Now count the branches. Each `if` has two ways out, so there are four. The first `if` used both. The
second used only one. Three of four branches is seventy five percent. Both tests use express orders,
so the other way out never ran.

Add a test for a standard order of exactly a hundred. Now all four branches run, and the report is
fully green.

```java
class ShippingCalculatorTest {
    private final ShippingCalculator calc = new ShippingCalculator();

    @Test
    void bigOrder() {
        calc.cost(new Order(120, true));
    }

    @Test
    void smallOrder() {
        assertTrue(calc.cost(new Order(50, true)) > 0);
    }

    @Test
    void standardOrder() {
        assertTrue(calc.cost(new Order(100, false)) < 10);
    }
}
```

| Suite | Lines in `cost` | Branches in `cost` |
|---|---|---|
| `bigOrder` + `smallOrder` | 6 of 6 = 100% | 3 of 4 = 75% |
| plus `standardOrder` | 6 of 6 = 100% | 4 of 4 = 100% |

## Enforce it with the build

A report only helps if someone reads it, so let the build read it. The verification task takes a
rule: the branch counter, the covered ratio, at least 80 percent. Gradle's `check` task doesn't run
that verification by itself, so wire it in, and a coverage drop fails the build.

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

tasks.check {
    dependsOn(tasks.jacocoTestCoverageVerification)
}
```

With the first two tests, branch coverage is 75 percent, and `check` fails. With the third test it
passes.

```mermaid {alt="Gradle task wiring: the test task is finalized by jacocoTestReport, and the check task depends on jacocoTestCoverageVerification." caption="Two lines of wiring."}
flowchart LR
  T["test"] -->|finalizedBy| R["jacocoTestReport"]
  K["check"] -->|dependsOn| V["jacocoTestCoverageVerification"]
  class T,K c5
  class R good
  class V hl
```

A rule can target the whole bundle, a package, a class, a source file or a method (`BUNDLE`,
`PACKAGE`, `CLASS`, `SOURCEFILE`, `METHOD`); the default is the whole bundle. The counter can be
`INSTRUCTION`, `LINE`, `BRANCH`, `COMPLEXITY`, `METHOD` or `CLASS`, and the value can be
`COVEREDRATIO` (a ratio from 0.0 to 1.0) or a count such as `MISSEDCOUNT`.

In **Maven**, the `check` goal does the same job. Its default phase is `verify`, and it halts the
build when a rule fails (`haltOnFailure` defaults to true):

```xml
<execution>
  <id>check</id>
  <goals>
    <goal>check</goal>
  </goals>
  <configuration>
    <rules>
      <rule>
        <element>BUNDLE</element>
        <limits>
          <limit>
            <counter>BRANCH</counter>
            <value>COVEREDRATIO</value>
            <minimum>0.80</minimum>
          </limit>
        </limits>
      </rule>
    </rules>
  </configuration>
</execution>
```

## Best practices

1. **Prefer branch coverage to line coverage.** A line can be green while half of its decision never
   ran. Our express line was exactly that.
2. **Avoid one vanity number for the whole project.** JaCoCo can set rules per package or per class,
   so new code gets a high bar and old code can't slide back.
3. **Keep generated code out of the numbers.** JaCoCo skips classes and methods marked with an
   annotation named `Generated` (any annotation with class or runtime retention whose name contains
   "Generated", since JaCoCo 0.8.3), and Lombok can add one when you switch it on in `lombok.config`:

   ```properties
   lombok.addLombokGeneratedAnnotation = true
   ```

   In Maven, the `check` goal also takes an `<excludes>` list of class files (wildcards `*` and `?`).
4. **Fail the build on a drop, and ratchet.** When coverage rises, raise the minimum, and never lower
   it.
5. **Treat low coverage as a map of untested code, not a grade.** Red lines tell you where to look.
   Green lines don't tell you anything is correct.

```mermaid {alt="Decision flow for reading a line in the report: a red line needs a test that reaches it; a green line with a yellow diamond needs a test for the other way out; a green line with green diamonds still needs assertions, which coverage cannot check." caption="What to do with each colour."}
flowchart TD
  Q["a line in the report"] --> R{"red?"}
  R -->|yes| W1["write a test<br/>that reaches it"]
  R -->|no| Y{"yellow diamond?"}
  Y -->|yes| W2["test the other<br/>way out"]
  Y -->|no| G["green: but does a test<br/>assert about it?"]
  class W1 bad
  class W2 warn
  class G hl
```

## Pitfalls: the report can't see assertions

The first pitfall is the big one: **a test with no assertion still counts as covered.** The `bigOrder`
test calls `cost` and checks nothing, yet it turns every line it touches green. Delete the assertions
from the other tests, and the report doesn't change. The `smallOrder` test does assert, but only that
the cost is above zero. Almost any wrong answer passes it, and coverage can't tell the difference.

The second is **chasing a hundred percent.** Tests written only to colour lines, like calling
getters, raise the number and buy nothing. A hundred percent of branches isn't proof either: it
means every branch ran once, with whatever values and checks you happened to write. Tests catch
bugs. Coverage finds the code nobody tested.

## Pitfalls: setup and scope

3. **The report isn't wired.** If the report task doesn't follow the test task, you get no report
   unless someone remembers to run it.
4. **The agent is missing.** Gradle attaches it to every `Test` task, but other tasks that fork a JVM
   need an explicit `jacoco { applyTo(tasks.run.get()) }`. In Maven, `forkCount` 0 (or `forkMode`
   never) keeps the agent out, so nothing is recorded. In a multi-module build, each project records
   its own data, so one combined report needs the JaCoCo Report Aggregation plugin
   (`jacoco-report-aggregation`).
5. **Generated code skews the totals,** because getters and builders count like your own logic. Use
   the annotation filter, or exclude those classes.
6. **Only one suite is measured.** A report only shows the test tasks you gave it. Each `Test` task
   writes its own exec file (`build/jacoco/<taskName>.exec`), and the aggregation plugin makes one
   report per suite name; it doesn't merge them.

If a number looks wrong, open the **Sessions** page in the report. It shows whether any execution
data was collected at all.

## Common questions

**"Does 100% coverage mean the code is tested?"** It means the code ran. Whether anything checked
the result is a different question, and the one the next lesson answers.

**"When is coverage not worth it?"** Chasing a number on trivial code (getters, generated classes,
`main` methods) costs more than it returns. Use coverage to find untested logic, then spend your
effort on assertions.

## Recap

Add the `jacoco` plugin with the report after `test`, read green, yellow and red, and prefer
branches to lines. Enforce a rule in `check`, keep generated code out, and use red lines as a map,
not a grade. But remember the van: the trace proves where it drove, not what it delivered.

**Coverage tells you what ran. It can't tell you what was checked.**

So how do we measure what was checked? Plant a bug on purpose, and see whether any test notices.
That is the next lesson: [mutation testing with PIT](/testing/pit-mutation-testing/).

## References

- [JaCoCo counters](https://www.jacoco.org/jacoco/trunk/doc/counters.html), [agent](https://www.jacoco.org/jacoco/trunk/doc/agent.html), [Maven plugin](https://www.jacoco.org/jacoco/trunk/doc/maven.html), [check goal](https://www.jacoco.org/jacoco/trunk/doc/check-mojo.html), [FAQ](https://www.jacoco.org/jacoco/trunk/doc/faq.html) and [change log](https://www.jacoco.org/jacoco/trunk/doc/changes.html)
- [Gradle JaCoCo plugin user guide](https://docs.gradle.org/current/userguide/jacoco_plugin.html)
- [Lombok configuration](https://projectlombok.org/features/configuration)
