Code coverage with JaCoCo and what it does not tell you
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite has 64 tests, and your team lead asks how much of the code they actually run. Without a number you are guessing, but a number alone can mislead too.
The jacoco-maven-plugin and its HTML report
Code coverage is the share of your code that ran while the tests ran. It is a good map of what is not tested, and a poor measure of how well the rest is tested.
Example 1 adds the jacoco-maven-plugin to pom.xml and shows what mvn verify prints.
Example 1 · pom.xml: the jacoco-maven-plugin
Runs in: the shoplite-api Maven project
<!-- pom.xml, inside <build><plugins> --><plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.13</version> <executions> <!-- 1. Before the tests: attach the JaCoCo agent to the test JVM --> <execution> <id>prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <!-- 2. After the tests (verify phase): write target/site/jacoco/index.html --> <execution> <id>report</id> <phase>verify</phase> <goals> <goal>report</goal> </goals> </execution> </executions></plugin>$ mvn verify ... [INFO] --- jacoco:0.8.13:prepare-agent (prepare-agent) @ shoplite-api --- [INFO] argLine set to -javaagent:C:\Users\asha\.m2\repository\org\jacoco\org.jacoco.agent\0.8.13\org.jacoco.agent-0.8.13-runtime.jar=destfile=C:\shoplite-api\target\jacoco.exec ... [INFO] Tests run: 64, Failures: 0, Errors: 0, Skipped: 0 ... [INFO] --- jacoco:0.8.13:report (report) @ shoplite-api --- [INFO] Loading execution data file C:\shoplite-api\target\jacoco.exec [INFO] Analyzed bundle 'shoplite-api' with 96 classes [INFO] BUILD SUCCESS
What this code does
prepare-agentsets theargLineproperty, which Surefire uses to start the test JVM with the JaCoCo agent; the agent writestarget/jacoco.exec.reportreads that file in theverifyphase and writes the HTML report totarget/site/jacoco/index.html, plus XML and CSV versions for tools.
JaCoCo (Java Code Coverage) is the usual coverage tool for Java. Its Maven plugin adds an agent, a small helper that watches the test JVM and records which code runs. Two goals do the work: prepare-agent before the tests and report after them.
Open target/site/jacoco/index.html. The report goes from packages to classes to methods to the source code, where green lines ran, red lines never ran, and yellow lines ran but missed some branches.
Order of execution
What mvn verify does
Put the steps in the order Maven and JaCoCo run them.
<argLine> itself, write <argLine>@{argLine} -Xmx512m</argLine>; otherwise the JaCoCo agent is dropped and the report says 0%.Line coverage vs branch coverage
Branch coverage is the share of decision outcomes that ran: every if, ?:, &&, || and switch case has a true side and a false side, and each counts separately.
Example 2 counts lines and branches by hand for deliveryCharge, to show what JaCoCo measures.
Example 2 · Line vs branch coverage, counted by hand
import java.util.Set;import java.util.TreeSet;
/** * A hand-made coverage counter, to see what JaCoCo measures. * JaCoCo does the same automatically by adding "probes" to the bytecode. */public class LineVsBranchDemo { static final Set<String> hitLines = new TreeSet<>(); static final Set<String> hitBranches = new TreeSet<>();
// 3 lines, and 4 branches (each condition can be true or false) static int deliveryCharge(int itemsTotal, boolean remoteArea) { hitLines.add("L1"); int charge = itemsTotal >= 499 ? 0 : 40; hitBranches.add(itemsTotal >= 499 ? "free=true" : "free=false"); hitLines.add("L2"); if (remoteArea) { hitBranches.add("remote=true"); hitLines.add("L3"); charge += 50; } else { hitBranches.add("remote=false"); } return charge; }
static void report(String testSet) { System.out.printf("%-28s lines %d/3 = %3d%% branches %d/4 = %3d%% %s%n", testSet, hitLines.size(), hitLines.size() * 100 / 3, hitBranches.size(), hitBranches.size() * 25, hitBranches); }
public static void main(String[] args) { deliveryCharge(299, true); report("Test 1: small, remote");
deliveryCharge(999, true); report("+ Test 2: big, remote");
deliveryCharge(999, false); report("+ Test 3: big, standard"); }}Test 1: small, remote lines 3/3 = 100% branches 2/4 = 50% [free=false, remote=true] + Test 2: big, remote lines 3/3 = 100% branches 3/4 = 75% [free=false, free=true, remote=true] + Test 3: big, standard lines 3/3 = 100% branches 4/4 = 100% [free=false, free=true, remote=false, remote=true]
What this code does
- The first test already ran all three lines, so line coverage says 100%. Branch coverage says 50%: the free-delivery side and the not-remote side never ran.
- It takes three tests to reach every branch outcome. JaCoCo counts these probes for you, and its report marks a line yellow when only some of its branches ran.
Line coverage is the share of lines that ran at least once.
One test can run every line of return total >= 499 ? FREE : CHARGE; while only ever taking one side. Branch coverage shows the gap; line coverage hides it. For business rules, branch coverage is the more honest number.
Predict the output
Work out the coverage
Count the lines that ran, then the true and false outcomes that ran.
Round 1 of 2
One test calls it with itemsTotal 999 and remoteArea false. What are the coverages?
A minimum coverage rule that fails the build
COVEREDRATIO is covered divided by total, from 0.00 to 1.00. A JaCoCo rule sets a minimum COVEREDRATIO for a counter such as LINE or BRANCH.
Example 3 adds the check goal with two minimums. The output shows the build failing because line coverage is 74%.
Example 3 · pom.xml: a coverage rule in the check goal
Runs in: the shoplite-api Maven project
<!-- a third <execution> inside the jacoco-maven-plugin --><execution> <id>check</id> <goals> <goal>check</goal> <!-- runs in the verify phase by default --> </goals> <configuration> <rules> <rule> <element>BUNDLE</element> <!-- the whole module --> <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> <excludes> <exclude>com/shoplite/ShopliteApiApplication.class</exclude> <!-- only starts Spring --> </excludes> </configuration></execution>$ mvn verify ... [INFO] --- jacoco:0.8.13:check (check) @ shoplite-api --- [INFO] Loading execution data file C:\shoplite-api\target\jacoco.exec [INFO] Analyzed bundle 'shoplite-api' with 95 classes [WARNING] Rule violated for bundle shoplite-api: lines covered ratio is 0.74, but expected minimum is 0.80 [INFO] BUILD FAILURE [ERROR] Failed to execute goal org.jacoco:jacoco-maven-plugin:0.8.13:check (check) on project shoplite-api: Coverage checks have not been met. See log for details.
What this code does
- Two limits on the whole module: at least 80% of lines and 70% of branches. Here lines are at 74%, so
mvn verify, and the CI build that runs it, fails. - The
excludeslist applies to this check only; the report still shows the excluded class. The application class only callsSpringApplication.run, so testing it adds nothing.
The check goal compares the numbers with the limits you set and fails mvn verify when one is not met. A rule names an element (the whole BUNDLE, each PACKAGE or CLASS), a counter (LINE, BRANCH, METHOD) and a minimum.
Set the limit a little below today's value, so it stops coverage from falling without blocking every change, and raise it slowly as tests improve. Exclude code that has nothing to test, such as the class with main that only starts Spring.
High coverage with no assertions: why 100% is not the goal
Mutation testing changes your code on purpose, for example >= to >, and checks that at least one test fails. A change no test notices is a gap in the assertions.
Example 4 runs two test suites with the same 100% coverage. Only one of them finds the bug at exactly Rs 499.
Example 4 · 100% coverage, zero bugs found
import java.math.BigDecimal;
public class NoAssertionsDemo { static final BigDecimal FREE_DELIVERY_FROM = new BigDecimal("499");
// BUG: ">" should be ">=": an order of exactly Rs 499 should get free delivery. static BigDecimal deliveryCharge(BigDecimal itemsTotal) { if (itemsTotal.compareTo(FREE_DELIVERY_FROM) > 0) { return new BigDecimal("0.00"); } return new BigDecimal("40.00"); }
public static void main(String[] args) { deliveryCharge(new BigDecimal("299.00")); deliveryCharge(new BigDecimal("999.00")); System.out.println("Suite A: coverage 100%, assertions 0, result: PASS (bug not found)");
// Test B: same inputs plus the boundary, and real checks. int failures = 0; String[][] cases = {{"299.00", "40.00"}, {"999.00", "0.00"}, {"499.00", "0.00"}}; for (String[] c : cases) { BigDecimal actual = deliveryCharge(new BigDecimal(c[0])); if (actual.compareTo(new BigDecimal(c[1])) != 0) { failures++; System.out.println(" FAIL total " + c[0] + ": expected " + c[1] + " but was " + actual); } } System.out.println("Suite B: coverage 100%, assertions 3, result: " + (failures == 0 ? "PASS" : "FAIL (bug found)")); }}Suite A: coverage 100%, assertions 0, result: PASS (bug not found) FAIL total 499.00: expected 0.00 but was 40.00 Suite B: coverage 100%, assertions 3, result: FAIL (bug found)
What this code does
- Suite A runs both lines of
deliveryChargeand asserts nothing, so a coverage tool reports 100% and the build is green, with the boundary bug still inside. - Suite B has the same coverage but checks results, including the boundary Rs 499.00, and finds the bug. Coverage could not tell these two suites apart.
Coverage counts code that ran, not code that was checked. A test that calls a method and asserts nothing gets full coverage and catches no bugs. Chasing a number invites such tests, plus tests for getters and generated code that cost time and add no safety.
Use the report to find important code with no tests, such as an untested error path in OrderService, then write tests with real assertions at the boundaries. Many teams aim for roughly 70 to 85% on business code; which branches are tested matters more than the exact number. A tool such as PIT runs mutation testing for you.
Find the bug
Tap the weak test
Each test reaches 100% coverage. Tap the line that makes it weak.
Tap the line that makes this test protect nothing.
Round 1 of 2Next step
Check your understanding
12 quick questions