Java Code Coverage

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 257 of 306

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:

CounterCountsUseful for
InstructionsSingle bytecode instructionsThe most detailed, language-neutral measure
LinesSource lines that have bytecodeA quick overview of untested code
BranchesEach outcome of if, switch, ? :, &&, ||Finding untested decisions
MethodsMethods (including constructors) with at least one instruction runSpotting dead or untested methods
ClassesClasses with at least one method runSpotting unused classes
ComplexityCyclomatic 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.
  • expressDelivery is always false, 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-agent sets the Maven property argLine to a -javaagent: option. Surefire passes argLine to 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.
  • report reads that file plus your compiled classes and writes target/site/jacoco/index.html, jacoco.xml and jacoco.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 markerMeaning
Green lineEvery instruction and branch on the line ran
Yellow lineThe line ran, but some branches did not
Red lineThe line never ran
Green diamondAll branches on the line were taken
Yellow diamondSome branches were taken; hover to see "1 of 2 branches missed"
Red diamondNo 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_COVERED is 2,2, the same 50 % branch coverage seen above.
  • METHOD_COVERED is 2 because 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.xml to 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 = true and coursesInCart >= 3 = true. The second takes isMember = 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 >= 3 is missed.
  • If someone changed >= 3 to >= 0, both tests would still pass. A test such as discountPercent(true, 2) returning 0 closes 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:

  • element chooses what each rule applies to, counter chooses what to count, and value chooses how to compare.
  • COVEREDRATIO with 0.80 means "at least 80 % of branches must be covered".
  • Add this execution after the report execution so the HTML report is still written when the check fails.

The most common options:

SettingOptions
elementBUNDLE (whole project), PACKAGE, CLASS, SOURCEFILE, METHOD
counterINSTRUCTION, LINE, BRANCH, COMPLEXITY, METHOD, CLASS
valueCOVEREDRATIO, 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 check rule.
  • The @Generated annotation only hides the marked main method; 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>
GoalData fileReport folder
prepare-agent + reporttarget/jacoco.exectarget/site/jacoco
prepare-agent-integration + report-integrationtarget/jacoco-it.exectarget/site/jacoco-it

How it works:

  • prepare-agent-integration runs just before Failsafe and points the agent at jacoco-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:

BranchTaken by
daysLate < 0 is truenegativeDaysAreRejected
daysLate < 0 is falseevery @CsvSource row
daysLate <= 3 is truerows 0 and 3
daysLate <= 3 is falserows 4, 10, 100
isPremium is truerows 10, true and 100, true
isPremium is falserows 4, 10, false, 100, false

How it works:

  1. The report pointed at the gaps. The three red lines matched three untested rules: negative input, the grace period and the premium discount.
  2. Boundary values. The rows 3 and 4 test both sides of the grace period, which catches an off-by-one mistake such as < GRACE_DAYS instead of <=.
  3. Beyond coverage. The 100, true row 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.
  4. The check protects the future. If someone adds a new if without a test, branch coverage falls below 80 % and mvn verify fails 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Code Coverage and get answers drawn from it.

Signed-in readers only.