Coverage and mutation testing

Senior Differentiator 4 min

On this page

The question

Is 100% code coverage enough?

30-second answer

No. Coverage shows which code ran during the tests, not that anything checked the result. A test with no assertion still counts, and a suite can reach 100% while missing a boundary value. So low coverage is a useful warning about untested code, but high coverage proves little. Mutation testing asks the harder question: would a test fail if this code were wrong?

Understand it

100% coverage that misses a bug

Predict

The rule: people aged 18 or older may vote. The code says age > 18. Two tests pass, and the report shows 100% line and branch coverage.

Does this suite catch the bug for an 18-year-old?
View as text

A line of code above two passing tests and a coverage report. The rule: people aged 18 or older may vote. The code says age > 18. Two tests pass, and the report shows 100% line and branch coverage. The learner first predicts whether the suite catches the bug.

Every line ran, and the condition went both ways: 30 made it true, 10 made it false. Coverage has nothing left to ask for. The report reads 100% lines and 2 of 2 branches.

canVote(18) returns false, which breaks the rule. No test calls it with 18, so the suite stays green and the report stays at 100%. A third row marks canVote(18) as returning false, untested.

A mutation tool changes > to >=. Both tests still pass, so this mutant survives, and that points straight at the untested boundary. The code line shows >= and both tests still pass.

Add assertTrue(canVote(18)). It fails on the wrong code, so you change > to >=, and now the suite really checks the rule. A third test now passes and the code reads >=.

A line of code above two passing tests and a coverage report. The rule: people aged 18 or older may vote. The code says age > 18. Two tests pass, and the report shows 100% line and branch coverage. The learner first predicts whether the suite catches the bug.

Every line ran, and the condition went both ways: 30 made it true, 10 made it false. Coverage has nothing left to ask for. The report reads 100% lines and 2 of 2 branches.

canVote(18) returns false, which breaks the rule. No test calls it with 18, so the suite stays green and the report stays at 100%. A third row marks canVote(18) as returning false, untested.

A mutation tool changes > to >=. Both tests still pass, so this mutant survives, and that points straight at the untested boundary. The code line shows >= and both tests still pass.

Add assertTrue(canVote(18)). It fails on the wrong code, so you change > to >=, and now the suite really checks the rule. A third test now passes and the code reads >=.

Takeaway: Coverage shows which code ran, not whether a test would notice it being wrong. A missing boundary test leaves the report at 100%.

Mutants killed and surviving

Step by step

Both tests pass on the original code, with 100% line and branch coverage. Now the tool changes the code in small ways, one mutant at a time.

Step 1 of 7
View as text

Two lines of code at the top, the tests with what each returned below them, and four tiles at the bottom, one per mutant, each waiting, killed or survived. The mutation score sits under the tiles.

Both tests pass on the original code, with 100% line and branch coverage. Now the tool changes the code in small ways, one mutant at a time.

Mutant 1 flips >= to <. Both tests fail, so a test noticed the change: this mutant is killed.

Mutant 2 changes / to *. shipping(20) returns 205 instead of 7, so one test fails: killed.

Mutant 3 returns 0 in place of the computed price. shipping(20) gives 0 instead of 7, so one test fails: killed.

Mutant 4 changes >= to >. No test uses exactly 50, so both still pass. This mutant survives, even with 100% coverage.

Three of four mutants were killed: a mutation score of 75%. The survivor shows exactly what is missing, a test at the boundary.

Add a test that shipping(50) is 0. It passes on the original and fails on mutant 4, which gives 10. Now every mutant is killed: 100%.

Two lines of code at the top, the tests with what each returned below them, and four tiles at the bottom, one per mutant, each waiting, killed or survived. The mutation score sits under the tiles.

Both tests pass on the original code, with 100% line and branch coverage. Now the tool changes the code in small ways, one mutant at a time.

Mutant 1 flips >= to <. Both tests fail, so a test noticed the change: this mutant is killed.

Mutant 2 changes / to *. shipping(20) returns 205 instead of 7, so one test fails: killed.

Mutant 3 returns 0 in place of the computed price. shipping(20) gives 0 instead of 7, so one test fails: killed.

Mutant 4 changes >= to >. No test uses exactly 50, so both still pass. This mutant survives, even with 100% coverage.

Three of four mutants were killed: a mutation score of 75%. The survivor shows exactly what is missing, a test at the boundary.

Add a test that shipping(50) is 0. It passes on the original and fails on mutant 4, which gives 10. Now every mutant is killed: 100%.

Takeaway: Mutation testing changes the code on purpose and reruns the tests. A surviving mutant is a change no test noticed, which marks a gap coverage cannot see.

What each measure answersLine coverage answers whether a line ran. Branch coverage answers whether each outcome of a condition ran. The mutation score answers whether a test would notice if the code were wrong.What do youwant to know?Did this line run?Line coverageDid each outcomerun?Branch coverageWould a test notice?Mutation score
What each measure answersLine coverage answers whether a line ran. Branch coverage answers whether each outcome of a condition ran. The mutation score answers whether a test would notice if the code were wrong.What do youwant to know?Did this line run?Line coverageDid each outcomerun?Branch coverageWould a test notice?Mutation score
What each measure answers

In code

class Shipping {
    static int shipping(int total) {
        if (total >= 50) return 0;       // mutant: total > 50 survives these two tests
        return total / 10 + 5;
    }
}

class ShippingTest {
    @Test
    void freeAboveFifty() { assertEquals(0, Shipping.shipping(100)); }

    @Test
    void chargedBelowFifty() { assertEquals(7, Shipping.shipping(20)); }
}
100% coverage, and a mutant that survives
@Test
void freeAtExactlyFifty() {
    assertEquals(0, Shipping.shipping(50));     // the boundary mutant returns 10 here
}
The test that kills it
One mutant through the toolThe tool changes greater-or-equal to greater and runs the tests that cover that line. All of them pass, so the mutant survives. Adding a test at exactly 50 makes one fail, so the mutant is killed.Change >= to >Run the testscovering itAll pass: survivesAdd a test at exactly50Run again: one failsMutant killed
One mutant through the toolThe tool changes greater-or-equal to greater and runs the tests that cover that line. All of them pass, so the mutant survives. Adding a test at exactly 50 makes one fail, so the mutant is killed.Change >= to >Run the testscovering itAll pass: survivesAdd a test at exactly50Run again: one failsMutant killed
One mutant through the tool
mvn verify                                      # with the JaCoCo plugin: target/site/jacoco/index.html
mvn org.pitest:pitest-maven:mutationCoverage    # PIT: target/pit-reports/index.html
Measure coverage and run mutation testing from the build

Solve it

Coverage is 92%, yet a refund bug shipped: what would have caught it?

refund(account, amount) should add the amount back. A release subtracted it instead, and the tests stayed green with 92% line coverage. The test calls refund and asserts assertNotNull(result).

  1. Separate executed from checked. Coverage counts lines that ran. The test ran every line of refund and checked almost nothing.
  2. Find the weak assertion. assertNotNull holds for a correct balance and for a wrong one, so the bug could not fail it.
  3. Let mutation testing show it. PIT replaces + with - in refund. The test still passes, so the mutant survives, which points straight at the weak test.
  4. Strengthen the test. Assert the exact new balance, and add the boundaries: a zero amount and a negative amount.
  5. Check. Rerun PIT: the mutant is killed. Use coverage to find untested code, and mutation score to judge the tests.
@Test
void refundWeak() {
    Account result = service.refund(new Account(100), 30);
 Wrong     assertNotNull(result);                                   // passes even when 30 is subtracted
}

@Test
void refundAddsTheAmount() {
    Account result = service.refund(new Account(100), 30);
 Right     assertEquals(130, result.balance());                     // kills the "+ to -" mutant
}

@Test
void refundRejectsNegativeAmount() {
    assertThrows(IllegalArgumentException.class, () -> service.refund(new Account(100), -5));
}
A test that runs the code, and one that checks it

How to answer

  • Use coverage to find untested code, not as proof of quality.
  • Setting a high target as a goal invites tests that assert nothing.
  • Boundaries and missing requirements stay invisible to coverage.

Common mistakes

  • Treating a coverage number as a measure of how well the code is tested.
  • Writing assertion-free tests to reach a coverage gate.

Follow-up questions

What is JaCoCo, and which coverage does it report?

The usual Java coverage tool. A Java agent instruments the bytecode as classes load, and the test run records what executed in a jacoco.exec file, which becomes an HTML or XML report. It counts instructions, lines, branches, methods and classes, plus cyclomatic complexity. Its check goal can fail the build below a threshold.

  • It works on bytecode, so it needs no change to your source.
  • Branch coverage counts the outcomes of each condition, which is stricter than lines.
  • Exclude generated code and plain data classes from the report.

See it in the infographic: 100% coverage that misses a bug

What is mutation testing, and how does PIT work?

It tests the tests. PIT makes small changes to the bytecode, called mutants, such as >= to > or a return value to 0. For each mutant it runs the tests that cover that line. If a test fails, the mutant is killed; if all pass, it survives and shows a gap. The score is the share killed. It is slow, so run it on changed code or nightly.

  • PIT uses coverage data to run only the tests that reach each mutant.
  • Some survivors are equivalent mutants, which behave the same as the original and can never be killed.
  • Run it with mvn org.pitest:pitest-maven:mutationCoverage.

See it in the infographic: Mutants killed and surviving

What coverage target would you set?

I would avoid one number for the whole codebase. A gate on new or changed code, often around 80%, stops things from getting worse without rewarding tests for getters. Review what is uncovered, since untested business rules matter far more than untested configuration or generated code.

Check yourself

1. A suite has 100% line and branch coverage, and every test passes. What can you conclude?
Show answers
  • Every line and branch ran during the tests.: Correct. That is all coverage measures. It says nothing about whether the results were checked.
  • The code has no bugs.: Incorrect. A suite can run a line with a wrong result and never notice, as with a missing boundary.
  • Every input value was tested.: Incorrect. A branch needs one value per outcome, so boundaries can go untested.
2. A mutation tool changes >= to > in your code, and all tests still pass. What does that tell you?
Show answers
  • No test checks the boundary, so the suite has a gap.: Correct. A surviving mutant is a change no test noticed.
  • The original code is wrong and must use >.: Incorrect. It says nothing about which is right, only that no test can tell them apart.
  • The tool failed to apply the change.: Incorrect. The change was applied; the tests simply passed with it.