liveBook · Manning

Code coverage

As explained in 100 Java Mistakes and How to Avoid Them

Code coverage is the fraction of program code elements executed during a test suite.

Code coverage measures the fraction of existing code executed by automated tests. JaCoCo instruments Java bytecode and reports coverage by lines, bytecode instructions, or branches. section 1.4

Treat coverage as a test-quality signal, not proof of correctness. Coverage above 80% generally becomes increasingly expensive, some statements are unreachable, and even 100% coverage does not show that the program is bug-free. section 1.4 section 1.8

Use coverage reports to:

  • Inspect whether conditional branches have tests, especially in series of if-else conditions. section 3.2
  • Add tests for uncovered branches, while recognizing that some defensive statements cannot be reached. section 1.4 section 3.2
  • Combine coverage with unit tests, static analysis, code reviews, dynamic analysis, and mutation coverage rather than relying on one metric. section 1.8

A passing test is not comprehensive coverage

A test that calls average(0, 10) once exercises the method, but the single passing case does not establish that every relevant behavior is tested. Coverage records execution; test assertions still determine what correctness is checked. section 1.4

class MyObject implements Cloneable {
  public MyObject clone() {
    try {
      return (MyObject) super.clone();
    } catch (CloneNotSupportedException e) {
      // never happens as we implement Cloneable
      throw new AssertionError(e);
    }
  }
}

Use the Cloneable example to see why a required catch-body statement may remain uncovered even though the exception is not expected to occur. section 1.4

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains line, instruction, and branch measurement, practical thresholds, unreachable code, and the limits of treating coverage as correctness.
Examples
Uses JaCoCo reports, an unreachable Cloneable catch statement, and a single test of an integer average method.
What it assumes
Assumes automated tests and Java code, while defining coverage measures and distinguishing execution measurement from bug detection.
What you can do after
Evaluate test completeness, target uncovered branches, and interpret high coverage without treating it as proof of correctness.
How it connects
Connects automated testing with unit testing, property testing, static analysis, dynamic analysis, code reviews, and mutation coverage.

Also explained in

Compare how 14 books explain code coverage →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.