Java Code Coverage
Java code coverage measures which parts of your code run while your tests run. It shows lines and branches that no test ever touches, so you know where bugs can hide. The standard tool for Java code coverage is JaCoCo, which works with Maven, Gradle and every major IDE.
This lesson explains the coverage counters, adds JaCoCo to a Maven project, reads the HTML report, shows why branch coverage matters more than line coverage, and makes the build fail when coverage drops. It ends by raising the coverage of a late-fee calculator from 50 % to 100 % of its branches. The examples use the JUnit setup from Java JUnit Basics.
What Java Code Coverage Measures
JaCoCo records coverage at the bytecode level and reports it with several counters:
| Counter | Counts | Useful for |
|---|---|---|
| Instructions | Single bytecode instructions | The most detailed, language-neutral measure |
| Lines | Source lines that have bytecode | A quick overview of untested code |
| Branches | Each outcome of if, switch, ? :, &&, || | Finding untested decisions |
| Methods | Methods (including constructors) with at least one instruction run | Spotting dead or untested methods |
| Classes | Classes with at least one method run | Spotting unused classes |
| Complexity | Cyclomatic complexity (number of independent paths) | Knowing how many tests a method needs |
A line can be fully covered, partly covered (some branches on it never ran) or missed. Here is a small class and one test:
package com.gocourse.shop;
public class ShippingCalculator {
public long shippingInPaise(long orderTotalInPaise, boolean expressDelivery) {
long shipping = orderTotalInPaise >= 50_000 ? 0 : 4_900; // free above ₹500
if (expressDelivery) {
shipping += 9_900;
}
return shipping;
}
}
package com.gocourse.shop;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class ShippingCalculatorTest {
@Test
void largeOrderShipsFree() {
assertEquals(0, new ShippingCalculator().shippingInPaise(60_000, false));
}
}
Coverage of shippingInPaise after running this one test:
Line Status Branches
long shipping = orderTotalInPaise >= 50_000 ? 0 : 4_900; partly covered 1 of 2
if (expressDelivery) { partly covered 1 of 2
shipping += 9_900; missed -
return shipping; covered -
Branch coverage: 2 of 4 (50 %)
How it works:
- The ternary operator has two outcomes. The test only takes the "free" one, so the small-order fee of ₹49 is never tested.
expressDeliveryis alwaysfalse, so the line that adds the express fee never runs.- The test passes, yet half of the decisions in the method are untested. Coverage makes that visible.
Add JaCoCo to a Maven Project
JaCoCo works as a Java agent. The prepare-agent goal attaches the agent to the JVM that runs your tests, and the report goal turns the recorded data into HTML, XML and CSV reports.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.6</version>
</plugin>
<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>
<goals>
<goal>report</goal> <!-- runs in the verify phase by default -->
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Run the build:
mvn verify
Output (shortened):
[INFO] --- jacoco:0.8.15:prepare-agent (prepare-agent) @ shop ---
[INFO] argLine set to -javaagent:/home/asha/.m2/repository/org/jacoco/org.jacoco.agent/0.8.15/org.jacoco.agent-0.8.15-runtime.jar=destfile=/home/asha/shop/target/jacoco.exec
[INFO] --- surefire:3.5.6:test (default-test) @ shop ---
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- jacoco:0.8.15:report (report) @ shop ---
[INFO] Loading execution data file /home/asha/shop/target/jacoco.exec
[INFO] Analyzed bundle 'shop' with 1 classes
[INFO] BUILD SUCCESS
How it works:
prepare-agentsets the Maven propertyargLineto a-javaagent:option. Surefire passesargLineto the test JVM, so the agent records every instruction your tests run.- The raw data goes to
target/jacoco.exec. It is binary and only useful as input for reports. reportreads that file plus your compiled classes and writestarget/site/jacoco/index.html,jacoco.xmlandjacoco.csv.
Note: If you set your own
<argLine>for Surefire, write it as<argLine>@{argLine} -Xmx1g</argLine>. Without@{argLine}, your value replaces JaCoCo's agent option and the report shows 0 % coverage.
Read the JaCoCo HTML Report
Open target/site/jacoco/index.html in a browser. The report starts with a table per package, then per class, then per method, and finally shows the source code with colours.
| Colour or marker | Meaning |
|---|---|
| Green line | Every instruction and branch on the line ran |
| Yellow line | The line ran, but some branches did not |
| Red line | The line never ran |
| Green diamond | All branches on the line were taken |
| Yellow diamond | Some branches were taken; hover to see "1 of 2 branches missed" |
| Red diamond | No branch on the line was taken |
The same numbers are available as CSV for scripts and CI tools:
cat target/site/jacoco/jacoco.csv
Output (columns shortened):
GROUP,PACKAGE,CLASS,...,BRANCH_MISSED,BRANCH_COVERED,...,METHOD_MISSED,METHOD_COVERED
shop,com.gocourse.shop,ShippingCalculator,...,2,2,...,0,2
How it works:
BRANCH_MISSED,BRANCH_COVEREDis2,2, the same 50 % branch coverage seen above.METHOD_COVEREDis2because the implicit constructor counts as a method and runs when the test creates the object.- CI services such as GitHub Actions or SonarQube usually read
jacoco.xmlto show coverage on pull requests.
Line Coverage vs Branch Coverage in Java
100 % line coverage does not mean every decision was tested. A condition with && sits on one line but has four branches: two for each operand.
package com.gocourse.shop;
public class DiscountPolicy {
/** Members buying 3 or more courses get 15 % off. */
public int discountPercent(boolean isMember, int coursesInCart) {
if (isMember && coursesInCart >= 3) {
return 15;
}
return 0;
}
}
package com.gocourse.shop;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class DiscountPolicyTest {
private final DiscountPolicy policy = new DiscountPolicy();
@Test
void memberWithFiveCourses() {
assertEquals(15, policy.discountPercent(true, 5));
}
@Test
void guestGetsNothing() {
assertEquals(0, policy.discountPercent(false, 5));
}
}
Coverage of discountPercent after these two tests:
Lines: 3 of 3 covered (100 %)
Branches: 3 of 4 covered (75 %)
Missed: isMember == true AND coursesInCart < 3
How it works:
- The first test takes
isMember = trueandcoursesInCart >= 3 = true. The second takesisMember = false, so Java skips the second check (short-circuit). - Every line has run, so line coverage is 100 %. But no test has a member with fewer than 3 courses, so one branch of
coursesInCart >= 3is missed. - If someone changed
>= 3to>= 0, both tests would still pass. A test such asdiscountPercent(true, 2)returning0closes the gap and reaches 4 of 4 branches.
Note: Coverage shows what your tests ran, not what they checked. A test with no assertions still produces coverage. Treat the report as a map of untested code, not as proof of quality.
Fail the Build With the JaCoCo check Goal
The check goal compares coverage against rules and fails the build when a rule is broken. This stops coverage from slowly dropping.
<execution>
<id>check</id>
<goals>
<goal>check</goal> <!-- runs in the verify phase by default -->
</goals>
<configuration>
<rules>
<rule>
<element>BUNDLE</element> <!-- the whole project -->
<limits>
<limit>
<counter>BRANCH</counter>
<value>COVEREDRATIO</value>
<minimum>0.80</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
With only the ShippingCalculatorTest from the first section, mvn verify fails:
[INFO] --- jacoco:0.8.15:check (check) @ shop ---
[INFO] Loading execution data file /home/asha/shop/target/jacoco.exec
[INFO] Analyzed bundle 'shop' with 1 classes
[WARNING] Rule violated for bundle shop: branches covered ratio is 0.50, but expected minimum is 0.80
[INFO] BUILD FAILURE
[ERROR] Failed to execute goal org.jacoco:jacoco-maven-plugin:0.8.15:check (check) on project shop: Coverage checks have not been met. See log for details.
How it works:
elementchooses what each rule applies to,counterchooses what to count, andvaluechooses how to compare.COVEREDRATIOwith0.80means "at least 80 % of branches must be covered".- Add this execution after the
reportexecution so the HTML report is still written when the check fails.
The most common options:
| Setting | Options |
|---|---|
element | BUNDLE (whole project), PACKAGE, CLASS, SOURCEFILE, METHOD |
counter | INSTRUCTION, LINE, BRANCH, COMPLEXITY, METHOD, CLASS |
value | COVEREDRATIO, MISSEDRATIO, COVEREDCOUNT, MISSEDCOUNT, TOTALCOUNT |
Exclude Generated Code From Coverage
Generated code, simple configuration classes and main launchers lower the numbers without telling you anything useful. You can exclude them in two ways.
1. By path in the plugin configuration (paths point to .class files):
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.15</version>
<configuration>
<excludes>
<exclude>com/gocourse/shop/generated/**</exclude>
<exclude>**/*Application.class</exclude>
</excludes>
</configuration>
<!-- executions as before -->
</plugin>
2. With an annotation. JaCoCo automatically ignores classes and methods marked with any annotation whose simple name contains Generated and whose retention is CLASS or RUNTIME.
package com.gocourse.shop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR})
public @interface Generated {
}
package com.gocourse.shop;
public class ShopApplication {
@Generated // launcher code: not counted in coverage
public static void main(String[] args) {
System.out.println("Shipping for ₹300: " + new ShippingCalculator().shippingInPaise(30_000, false));
}
}
Output when the program runs:
Shipping for ₹300: 4900
How it works:
- Path excludes remove whole classes from every report and every
checkrule. - The
@Generatedannotation only hides the markedmainmethod; the class's other code is still measured. - Exclude code because it is generated or trivial, never just to hit a number.
Coverage for Integration Tests
Maven Failsafe also reads the argLine property, so the agent set by prepare-agent records your *IT classes too. With the setup above, mvn verify writes unit and integration test data into the same jacoco.exec, and the report goal in the verify phase includes both.
If you prefer separate reports, JaCoCo has matching goals for integration tests:
<execution>
<id>prepare-agent-integration</id>
<goals>
<goal>prepare-agent-integration</goal> <!-- pre-integration-test phase -->
</goals>
</execution>
<execution>
<id>report-integration</id>
<goals>
<goal>report-integration</goal> <!-- verify phase -->
</goals>
</execution>
| Goal | Data file | Report folder |
|---|---|---|
prepare-agent + report | target/jacoco.exec | target/site/jacoco |
prepare-agent-integration + report-integration | target/jacoco-it.exec | target/site/jacoco-it |
How it works:
prepare-agent-integrationruns just before Failsafe and points the agent atjacoco-it.exec.- Comparing the two reports shows which code only integration tests reach, such as the SQL code from Java Integration Testing.
Real-World Example: Raise Java Code Coverage of a Late-Fee Calculator
A course library charges ₹20 per day for late returns after a 3-day grace period, halves the fee for premium members and caps it at ₹500. The team wants at least 80 % branch coverage.
package com.gocourse.library;
public class LateFeeCalculator {
static final long DAILY_FEE_PAISE = 2_000; // ₹20 per day
static final long MAX_FEE_PAISE = 50_000; // ₹500 cap
static final int GRACE_DAYS = 3;
public long feeInPaise(int daysLate, boolean isPremium) {
if (daysLate < 0) {
throw new IllegalArgumentException("daysLate cannot be negative: " + daysLate);
}
if (daysLate <= GRACE_DAYS) {
return 0;
}
long fee = (daysLate - GRACE_DAYS) * DAILY_FEE_PAISE;
if (isPremium) {
fee = fee / 2;
}
return Math.min(fee, MAX_FEE_PAISE);
}
}
The first version of the test checks only one case:
@Test
void tenDaysLate() {
assertEquals(14_000, new LateFeeCalculator().feeInPaise(10, false));
}
mvn verify with the check rule from above:
[WARNING] Rule violated for bundle library: branches covered ratio is 0.50, but expected minimum is 0.80
[INFO] BUILD FAILURE
The method has three if statements, so 6 branches. The single test takes the "false" side of each one: 3 of 6. The HTML report marks the throw, return 0 and fee / 2 lines in red. Each red line is a missing test case, so the team writes them as a parameterized test (see JUnit Parameterized Tests):
package com.gocourse.library;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@DisplayName("LateFeeCalculator")
class LateFeeCalculatorTest {
private final LateFeeCalculator calculator = new LateFeeCalculator();
@ParameterizedTest(name = "{0} days late, premium={1} -> {2} paise")
@CsvSource({
"0, false, 0", // returned on time
"3, false, 0", // last day of the grace period
"4, false, 2000", // first charged day
"10, false, 14000", // 7 charged days
"10, true, 7000", // premium pays half
"100, false, 50000", // 97 days would be 194000, capped at 50000
"100, true, 50000" // half of 194000 is 97000, still capped
})
void calculatesFee(int daysLate, boolean isPremium, long expectedPaise) {
assertEquals(expectedPaise, calculator.feeInPaise(daysLate, isPremium));
}
@Test
@DisplayName("negative days are rejected")
void negativeDaysAreRejected() {
IllegalArgumentException error = assertThrows(IllegalArgumentException.class,
() -> calculator.feeInPaise(-1, false));
assertEquals("daysLate cannot be negative: -1", error.getMessage());
}
}
mvn verify now passes the check:
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- jacoco:0.8.15:report (report) @ library ---
[INFO] Analyzed bundle 'library' with 1 classes
[INFO] --- jacoco:0.8.15:check (check) @ library ---
[INFO] Analyzed bundle 'library' with 1 classes
[INFO] All coverage checks have been met.
[INFO] BUILD SUCCESS
Branch coverage, step by step:
| Branch | Taken by |
|---|---|
daysLate < 0 is true | negativeDaysAreRejected |
daysLate < 0 is false | every @CsvSource row |
daysLate <= 3 is true | rows 0 and 3 |
daysLate <= 3 is false | rows 4, 10, 100 |
isPremium is true | rows 10, true and 100, true |
isPremium is false | rows 4, 10, false, 100, false |
How it works:
- The report pointed at the gaps. The three red lines matched three untested rules: negative input, the grace period and the premium discount.
- Boundary values. The rows
3and4test both sides of the grace period, which catches an off-by-one mistake such as< GRACE_DAYSinstead of<=. - Beyond coverage. The
100, truerow adds no new branch, because every branch was already covered. It is still valuable: it proves the cap applies after the premium discount. Good tests follow the rules of the business, and coverage confirms that nothing was forgotten. - The check protects the future. If someone adds a new
ifwithout a test, branch coverage falls below 80 % andmvn verifyfails before the change is merged.
The next lessons move from testing to building: Maven in Java explains how the pom.xml, phases and plugins used here fit together.