November 26, 202610 minutes
Part 2 of 5
A 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.
This is the first of two lessons on measuring your tests. Here we measure what ran. The next one, mutation testing with PIT, measures what was checked. Both build on unit testing with JUnit 5.
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.
public record Order(double total, boolean express) {}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.
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.
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.
A fully green map means nothing was skipped. It says nothing about delivery.
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.
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.
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:
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:
<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.
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.
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 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.
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.
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% |
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.
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.
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):
<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>Prefer branch coverage to line coverage. A line can be green while half of its decision never ran. Our express line was exactly that.
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.
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:
lombok.addLombokGeneratedAnnotation = trueIn Maven, the check goal also takes an <excludes> list of class files (wildcards * and ?).
Fail the build on a drop, and ratchet. When coverage rises, raise the minimum, and never lower it.
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.
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.
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).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.
“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.
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.