LESSON 9

Code Coverage and Mutation Testing

Measure what tests execute, understand what coverage does and does not prove, and use mutation testing and risk-based thresholds to judge test strength.

Introduction

“We have 90% coverage” sounds reassuring. It means that 90% of the code was executed during tests. It does not mean 90% of the behavior was verified. A test with no assertions can achieve full coverage of a function and detect nothing.

This distinction is crucial in the age of AI-generated tests, which can raise coverage numbers rapidly without raising confidence. Used well, coverage is a useful diagnostic. Used as a target, it is easy to game, deliberately or not.

Learning Objectives

  • Explain the types of coverage and what each measures.
  • Interpret coverage reports to find untested code and risk.
  • Explain why high coverage does not guarantee good tests (and Goodhart’s law applied to it).
  • Use mutation testing to measure whether tests detect defects.
  • Set sensible, risk-based coverage expectations.
  • Use AI to analyze coverage gaps and survivors without chasing numbers.

1. Types of Coverage

Type Measures Notes
Line (statement) Which lines ran Easy to measure; weakest signal
Branch Which outcomes of conditions ran (true and false of each if) More informative than line coverage
Function Which functions were called Coarse
Condition / MC/DC Combinations of sub-conditions Used in safety-critical software
Requirement coverage Which requirements have tests Different idea; measured by traceability
Risk coverage Which identified risks have tests The most meaningful, and least automated

Example. This function shows 100% line coverage after one test, although one of its two outcomes was never exercised:

1
2
3
4
5
def classify(body):
    return "TOO_LONG" if len(body) > 10_000 else "OK"

def test_ok():
    assert classify("hello") == "OK"

The single line executes, so line coverage reports it as covered, yet the “too long” outcome was never exercised. Line coverage hides untaken outcomes whenever several share one line (conditional expressions, short-circuit operators, one-line if statements). Branch coverage narrows this gap, but tools differ in granularity: some track only jumps between lines and still miss outcomes within a single line. Treat even branch coverage as a hint, and complement it with mutation testing (section 5).

2. What Coverage Does and Does Not Tell You

What it tells you

  • Code that no test ever executes. Low or zero coverage is a reliable signal of an untested area.
  • Where to look for missing tests, especially in recently changed code.
  • Trends: a falling coverage on changed code is a warning sign.

What it does not tell you

  • Whether the tests assert anything meaningful about the executed code.
  • Whether requirements are covered; code that is missing has no coverage.
  • Whether combinations and data variations have been tried.
  • Whether integration behavior is correct, since a unit test can execute a line against a mock and say nothing about reality.

Coverage is a necessary but not sufficient indicator: low coverage proves there are gaps; high coverage does not prove their absence.

3. Goodhart’s Law and Coverage Targets

When a measure becomes a target, it stops being a good measure. A mandated 90% threshold leads to:

  • Assertion-free tests written only to execute lines.
  • Tests for trivial code (getters, constants) that cannot fail.
  • Generated tests that mirror the implementation.
  • Time spent chasing the last few percent in code that is hard to test and low in risk.

A more useful approach:

  • Use a modest floor (for example, no decrease on changed code, or a project-wide minimum such as 70-80%) as a guardrail against neglect.
  • Apply higher scrutiny to high-risk code (authorization, tenant scoping, import logic) than to glue code.
  • Review uncovered lines in each pull request, and ask whether the gap matters.
  • Never use coverage to evaluate individuals or teams.

(The figures above are illustrative. Pick thresholds with your team based on risk and history.)

4. Reading a Coverage Report

Do not just look at the percentage. Look at:

  1. The uncovered lines and branches in high-risk modules. Which of them handle errors, limits, or authorization?
  2. Error-handling paths: these are often untested, and frequently where production failures originate.
  3. Changed code: coverage of the diff matters more than the global number.
  4. Files with zero coverage: are they dead code (delete it) or untested risk?
  5. Coverage by test level: code covered only by E2E tests is slow to verify and hard to diagnose.

Combine with the risk table from lesson 3: a 60% covered admin screen is less worrying than a 95% covered importer with an uncovered authorization branch.

5. Mutation Testing

Mutation testing measures how well tests detect defects. A tool makes many small changes to the code (mutants): flipping > to >=, replacing and with or, removing a statement, changing a constant. It runs the tests against each mutant.

  • If a test fails, the mutant is killed (good: the tests noticed).
  • If all tests pass, the mutant survives (a gap: the tests would not notice this bug).

The mutation score is the percentage of mutants killed.

1
2
3
4
5
6
7
# Original
if len(body) > 10_000:
    return "TOO_LONG"

# Mutant: boundary changed
if len(body) >= 10_000:
    return "TOO_LONG"

If no test checks a body of exactly 10,000 characters, this mutant survives. That is precisely the boundary test lesson 2 told you to write. Mutation testing finds the missing boundary tests automatically.

Practical points:

  • It is slow, since the suite runs many times. Run it on changed or high-risk modules, nightly or on demand, not on every commit.
  • Not every survivor matters. Some are equivalent mutants (the change does not alter behavior) or in code that is irrelevant. Triage them.
  • Many ecosystems have mature tools (for example, mutmut and cosmic-ray for Python, Stryker for JavaScript and .NET, PIT for Java).
  • It is the best antidote to assertion-free generated tests: they achieve coverage but kill no mutants.

6. A Practical Approach

  1. Measure branch coverage in CI; show coverage of changed lines in each pull request.
  2. Set a floor and a no-regression rule, not a heroic target.
  3. Review the uncovered parts of high-risk modules regularly.
  4. Run mutation testing on the highest-risk modules (importer, tenant scoping, authorization) and triage survivors.
  5. Track requirement and risk coverage through traceability, since code coverage cannot show missing features.
  6. Treat coverage drops and surviving mutants as questions, not as failures.

7. Using AI With Coverage Analysis

AI is helpful for interpreting reports and suggesting tests for gaps, but it will happily write tests that merely execute the uncovered lines.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Act as a test analyst.

Inputs:
- Coverage report excerpt (uncovered lines and branches): [paste]
- Source code of the module: [paste]
- Requirements and risk ranking for this module: [paste]
- Surviving mutants from a mutation run: [paste]

Tasks:
1. For each uncovered branch or surviving mutant, explain the behavior
   that is not verified, and whether it matters given the risk.
2. Group the gaps: important, minor, dead code, equivalent mutant.
3. For the important ones, propose a test case with an expected result
   derived from the requirement, not from the current code.
4. Identify any uncovered code that looks unreachable and could be
   removed.
Do not write tests whose only purpose is to execute lines.

Verify each proposed test against the requirement, and re-run the mutation tool to confirm that the survivor is now killed.

8. Practical Exercise

For SignalDesk (or your project):

  1. Measure line and branch coverage and produce a report. Identify the five uncovered areas that carry the most risk.
  2. Pick one function with high line coverage and test it by manual fault injection (as in lesson 4). Record whether coverage was misleading.
  3. Run a mutation testing tool on the import validation and tenant-scoping modules. Record the mutation score and triage the survivors into: add a test, equivalent mutant, or irrelevant.
  4. Use the AI prompt to propose tests for the important survivors; verify them against requirements, add them, and rerun the tool.
  5. Define your coverage policy: floor, no-regression rule, higher scrutiny areas, and what happens when a threshold is missed.
  6. Add changed-line coverage to your pull request report.

Verification

You are ready to continue when:

  • Branch coverage is measured and visible on pull requests.
  • High-risk modules have been mutation tested and survivors triaged.
  • The coverage policy is written, risk-based, and does not rank people.
  • No test was added solely to execute lines.
  • You can explain, with an example from your code, why high coverage can mislead.

Key Takeaways

  • Coverage measures execution, not verification.
  • Low coverage is a reliable warning; high coverage is not a guarantee.
  • Targets distort behavior; use a modest floor and focus on risk and changed code.
  • Mutation testing measures whether tests detect defects and exposes weak assertions.
  • Use AI to analyze gaps, but derive expected results from requirements.

What’s Next?

Even the best suite lets some defects escape. Next, we look at defect analysis: how to report, triage, analyze, and learn from defects so that the same failures do not recur.