top of page

Mutation Testing: Testing Your Tests

Shift Quality Editorial
Jun 17
9 min read

Updated: Oct 18

A pricing module has 95% line coverage, and the line that applies the bulk discount is covered. The test for it orders 150 units and checks the discounted price. The specification says the discount starts at 100 units or more, but the code says quantity > 100. A customer who orders exactly 100 units pays full price, and every test passes.

Coverage can't catch this, because coverage only records that the line ran. Mutation testing asks a different question: if this line were slightly wrong, would any test notice? A mutation tool changes > to >= and reruns the tests. They all still pass, because none of them uses 100. That surviving mutant points straight at the missing boundary test, and writing that test from the specification exposes the bug.

This post shows how to read what a mutation tool tells you, how to start without it turning into a research project, and how to keep it cheap enough to keep using.

What a surviving mutant tells you

A mutation tool makes one small change to your code, such as flipping a comparison, removing a call or replacing a return value. That change is a mutant. The tool runs your tests against it. If any test fails, the mutant is killed. If every test passes, the mutant survives. Each survivor is a specific change your tests can't tell apart from the real code.

Here's the mutant from the opening, as a tool like Stryker would report it:

src/pricing/discount.ts:14
- if (quantity > 100) {
+ if (quantity >= 100) {
Survived. Covered by 3 tests: all passed.

And here's the test that kills it, written from the specification rather than from the code:

test("bulk discount starts at exactly 100 units", () => {
  expect(unitPrice({ quantity: 99 })).toBe(10.00);
  expect(unitPrice({ quantity: 100 })).toBe(9.00);
});

Run it against the real code and it fails at 100. The mutant didn't create the bug. It showed where the tests weren't looking.

There's evidence that these small artificial faults tell you something about real ones. Just and colleagues looked at 357 real faults in five open-source projects and found a statistically significant correlation between a test suite detecting mutants and detecting real faults, independently of code coverage. Google's analysis of almost 15 million mutants found that developers who received mutants wrote more tests, and that mutants were coupled with real high-priority faults: had mutation testing been used on the changes that introduced those faults, it would have reported a surviving mutant.

The test: take one surviving mutant from your own code and write the test that kills it. If writing it makes you check the specification, the mutant has found a real gap.

Read two scores, not one

Most tools report a single mutation score, and that one number mixes two different problems together. Stryker's metrics separate them:

  • Mutation score = detected / valid. Detected is killed plus timeout. Valid is every mutant that compiled and ran.

  • Mutation score based on covered code = detected / covered. It only counts mutants on code that some test actually runs.

The gap between them tells you which problem you have. A mutant with no coverage means no test runs that code at all. That's a coverage gap, and your coverage report already shows it. A mutant that survived despite being covered means a test ran the code and didn't check the result. That's an assertion gap, and only mutation testing shows it.

In the worked example below, the pricing module scores 73% overall and 80% on covered code. The 18 uncovered mutants are a coverage problem. The 38 covered survivors are tests that run code without checking it, and they're where the opening bug was hiding.

The test: after your first run, write down both scores. If the covered-code score is much higher than the overall score, start with coverage. If both are low, your tests are running code without checking the results, and that's the more valuable thing to fix.

Start with one module and a time budget

Running mutation testing across a whole codebase is how most adoptions stall. Every mutant needs a test run, so the cost grows with the number of mutants multiplied by the time to run the tests for each one. Modern tools reduce this a lot. PIT first measures line coverage, then uses that data, along with test timings, to pick the tests targeted at each mutated piece of code. Stryker uses coverage analysis in the same way. Even so, a large codebase produces thousands of mutants.

Pick one module using two questions: what's the most expensive thing to get wrong here, and what changes most often? Pricing, permissions, billing and data transformations usually come first. UI layout and generated code usually come last, because mutating a style or a selector rarely says anything useful.

Then set a time budget before you start. Run the tool on the module once, note how long it takes, and decide whether that fits in a nightly job or needs to wait for a weekly one. If the first run is too slow, narrow the scope to the files that matter, not the mutators. Removing mutators hides the kinds of gaps you're trying to find.

The test: can you name the module, the reason you chose it, and the time it takes to run? If you can't name the reason, pick a different module.

Triage survivors into four kinds

The report gives you a list of survivors, and the useful work is sorting them. Almost every survivor is one of four kinds:

Kind

How to recognise it

What to do

Missing check

The code runs in a test, but nothing asserts on the result it affects (often toBeTruthy() or "no exception thrown")

Tighten the assertion to the actual expected value

Missing case

A boundary or branch the tests never use: the exact threshold, an empty list, an error path

Add the case, written from the specification, not the code

Dead or redundant code

Mutating it changes nothing because nothing uses the result

Delete the code, which deletes the mutants

Equivalent mutant

The change can't alter behaviour, such as i < n becoming i != n in a loop that counts up by one from zero

Mark it ignored, with a comment saying why

Equivalent mutants are the long-standing problem in mutation testing. Some can be removed automatically: in one study, using a compiler to spot mutants that produce identical binaries discarded more than 7% of all mutants as equivalent. But that technique found only about 30% of the equivalent mutants humans identified, so most still need someone to judge them. Mark the ones you've judged so they stop counting. Stryker supports a // Stryker disable comment, and disabled mutants appear as ignored and "don't influence your mutation score". That way the next person doesn't triage the same one again.

The test: for every survivor you decide not to fix, can you say which of the four kinds it is? "Not worth it" is a valid decision, but only once it's written down. Otherwise the same survivor turns up in every run.

Run it on the diff, at review time

The approach that has worked at the largest scale doesn't mutate the whole codebase. Google mutates only the code changed in a review. It filters out mutants that developers are unlikely to care about, limits how many are shown per line and per review, and posts the survivors in the code review itself. In 2018 the system was used by 6,000 engineers. By 2021 it was used by more than 24,000 developers on more than 1,000 projects.

Two things make this work. A reviewer sees a few survivors about code they're reading anyway, rather than a nightly report about code nobody remembers. And the cost is limited by the size of the change, not the size of the codebase.

You don't need Google's infrastructure to do a version of this. Stryker's --incremental mode, available since version 6.2, tracks your changes and only runs mutation testing on changed code, reusing earlier results for the rest. PIT can reuse results from earlier runs in the same way, for example treating a mutant as still killed if neither the class nor the killing test has changed. Run the incremental job on pull requests that touch your chosen module, and run the full module on a schedule.

The test: how long does the incremental run take on a typical pull request? If it fits within your normal CI time, run it on every pull request that touches the module. If it doesn't, run it nightly and post the survivors on the pull requests that introduced them.

Use the score as a floor, not a target

Once a team sees a mutation score, someone will want to set a target for it. Stryker's defaults are deliberately gentle: 80% or more is reported as high, below 60% as low, and break (the score below which the build fails) is null, so it never fails the build on score by default.

A target encourages people to write tests just to kill mutants: assertions that pin down implementation details, or tests for code that should have been deleted. A floor guards against something worse, which is the suite quietly getting weaker. Set break a few points below your current score for the module. A drop then fails the build and gets looked at, but nobody is pushed to chase the number upwards.

The test: if your score rose ten points next month, could you name the changes that caused it? If the answer is "lots of new tests", look at a few. Tests that kill mutants without checking anything a user cares about aren't progress.

A worked example

Here is the pricing module from the opening. It's a composite: the module, numbers and timings are illustrative, and the scores use Stryker's definitions.

First run: src/pricing/ (line coverage 95%)
Mutants: 212 total, 4 invalid (compile/runtime error), 208 valid
Killed 150 + timeout 2       = detected 152
Survived 38 + no coverage 18 = undetected 56
Mutation score:               152 / 208 = 73%
Score on covered code:        152 / 190 = 80%

Triage
No coverage (18)
  11  currency-conversion failure path: no test for a failed rate lookup
      -> one test file for the failure paths
   7  legacyRounding(): no callers since last year
      -> deleted the function
Survived (38)
  14  discount tier comparisons (> vs >=): tests use mid-tier quantities
      -> boundary tests at 99/100, 499/500, 999/1000
         The 100-unit test FAILED against the real code: the bug.
  10  tax calculation: tests assert the total is truthy
      -> assert the exact total
   6  equivalent (loop bounds, i < n vs i != n)
      -> // Stryker disable, with reason
   4  string literals in log messages
      -> // Stryker disable, with reason
   4  rounding mode in a display-only helper
      -> left visible as accepted survivors

Second run
Valid 191 (7 deleted, 10 ignored)   Detected 187   Score 98%
Floor set: break = 93

The score went from 73% to 98%, but that's the least useful result. The run found a real pricing bug, deleted a dead function, added failure-path tests to a part of the module nobody had tested, and left a written record of the 14 mutants the team chose not to fix. The four rounding survivors are still visible, so if that helper ever becomes customer-facing, they'll show up again.

Mutation testing shows whether tests would notice a bug, not just whether code ran. In the composite pricing module with 95% line coverage, a mutant changing quantity greater than 100 to greater than or equal to 100 survived because no test used exactly 100 units; the boundary test written from the specification exposed a real bug. Read two scores: overall mutation score, 152 of 208 valid mutants detected (73%), and the score on covered code, 152 of 190 (80%). Triage survivors into four kinds: missing check, missing case, dead code and equivalent mutant. Run incrementally on changed code at review time, as Google does across more than 24,000 developers. After triage the score was 98%, with a floor set at 93.

What to do this week

Pick one module by cost of failure and change rate, and run Stryker, PIT, mutmut or the tool for your language on it once. Record the run time and both scores. Triage the survivors into the four kinds, fix the missing checks and missing cases first, delete dead code, and mark equivalent mutants as ignored with a reason. Then set a floor a few points below the new score, and turn on incremental runs for pull requests that touch the module. The Risk-Based Test Strategy Worksheet helps you choose which module goes first.

Final takeaway

Coverage tells you which code ran. Mutation testing tells you whether a test would notice if that code were wrong, and the gap between the two is where tests run code without checking it. Start with one critical module and a time budget. Read the overall score and the covered-code score separately. Sort every survivor into one of four kinds, and write down the ones you choose not to fix. Run it on changed code at review time so the cost stays small, and set the score as a floor, not a target. Above all, read the survivors, because that's where the bugs turn up.

Sources

Related reading

Keep learning. This article is part of the Advanced Quality Engineering path in the ShiftQuality Learning Center. Take quality from a team chore to an organizational property.

bottom of page