404human Experience Projects Writing Build logs Learning Books Progress
Rust · Zola
zsh · 404human@dev:~ Tab complete · ↑↓ history · type help

Mutation testing explained: proving your tests actually catch bugs

What mutation testing is, why 95% code coverage still lets critical bugs ship, how to run it in Rust and JS, and how to use targeted mutation harnesses.

Published
Read time
5 min read
Kind
guide
Topics

A test suite can report 95% line coverage, stay bright green on every pull request, and still let someone delete an authorization check without a single test failing.

That happens far more often than teams admit. Line coverage only measures whether the CPU walked over a line of code—it says nothing about whether any assertion would complain if that line broke.

Mutation testing flips the question around: instead of testing your code with your tests, it tests your tests by intentionally breaking your code.

How mutation testing works (in 4 steps)

A mutation testing tool—or a targeted security mutation harness—runs a simple loop:

1. Run test suite on clean code  ──► Must pass (baseline)
2. Inject ONE small bug (mutant) ──► e.g. flip `>=` to `>`, replace check with `true`
3. Re-run relevant tests         ──►
     ├── At least 1 test FAILS   ──► Mutant KILLED  (your tests caught the bug)
     └── All tests still PASS    ──► Mutant SURVIVED (real blind spot in your suite!)
4. Revert change & repeat for next mutant

Your mutation score is simply:

mutation_score = killed_mutants / (killed_mutants + survived_mutants)

(Ignoring mutants that fail to compile or are mathematically identical to the original code—known as equivalent mutants.)

Why code coverage lies (a 6-line example)

Look at this rate-limit guard in Rust:

pub fn allow_request(count: u32, limit: u32) -> bool {
    if count >= limit {
        return false;
    }
    true
}

Suppose your unit test checks allow_request(1, 5) == true and allow_request(10, 5) == false:

  • Line coverage: 100% (every single line and branch executed!).
  • Mutation test (>= mutated to >): allow_request(1, 5) is still true, allow_request(10, 5) is still false — mutant SURVIVES!

The off-by-one boundary (allow_request(5, 5) == false) was never tested. Line coverage gave a false gold star; one boundary mutant exposed the gap in two seconds.

Common mutant operators that expose real bugs

Mutation categoryOriginal codeMutated codeWhat a surviving mutant reveals
Boundary fliplen <= MAX_BYTESlen < MAX_BYTESMissing exact-limit boundary test
Boolean negationif !token.is_revoked()if trueAuth/revocation check never asserted negatively
Return-value swapreturn Err(Forbidden)return Ok(())Error path ran or was mocked away without checking status
Statement deletionverify_hmac(sig, body)?;(line deleted)Test passed a valid signature only, never tested a tampered body
Arithmetic tweakretries + 1retries - 1Loop/backoff math not asserted across multiple attempts

Two ways to run mutation testing in practice

1. Automated tooling on critical modules

Modern mutation runners do not require editing code by hand:

  • Rust: cargo-mutants — compiles and runs targeted diffs (cargo mutants --in-diff git.diff or --file src/auth.rs).
  • TypeScript / JavaScript: StrykerJS — supports Vitest, Jest, and Playwright suites with incremental caching.
  • Python: mutmut or cosmic-ray.
  • Go: gremlins (focuses on fast targeted mutations).

Practical tip: Never run a mutator across an entire 100k-line repo on day one. Point it at one high-stakes file first—your auth middleware, webhook verifier, parser, or ledger math—and inspect the first 10 surviving mutants. You will find real missing tests inside five minutes.

2. Targeted security mutation harnesses (what we use in CI)

Automated mutators generate hundreds of small syntactic mutants, many of them noisy (like changing log strings or metrics labels). For security controls and durability invariants, a hand-written mutation harness is often faster and higher-signal.

Across seven repositories in this workspace, we built a mutation-proof verification standard (detailed in how we proved our security attack tests fail when protections are removed):

  • Instead of mutating random syntax, the harness disables named security protections one at a time (e.g., turning off SSRF DNS-rebinding checks, body-size ceilings, rate-limit keying, or RLS tenant guards) behind a test-only feature flag or controlled patch.
  • For each disabled protection, the matching attack test must fail.
  • If an attack test still passes when its protection is turned off, the test itself is broken (testing the wrong endpoint, mocked out, or asserting status 200 on an unrelated path)—and CI fails.

This catches the exact failure mode we hit earlier when an integration test printed PASS while reading the wrong record ID (my test said PASS).

What mutation testing is NOT good for

Be realistic about the trade-offs so you do not waste team morale chasing 100% mutation scores:

  • Equivalent mutants: Sometimes a mutation does not change observable behavior (for example, changing a capacity hint Vec::with_capacity(16) to Vec::with_capacity(0) only affects allocations, not correctness). Trying to “kill” equivalent mutants wastes time.
  • UI layout and glue code: Mutating CSS classes, log formatting, or thin CLI argument plumbing produces low-value noise.
  • Slow end-to-end suites: Every mutant requires re-running affected tests. If a test suite takes 4 minutes to boot Docker, 200 mutants will take hours. Keep core logic in fast unit/property tests and use targeted harnesses for integration/security boundaries.

Where to start this afternoon

  1. Pick the one module in your codebase where a silent regression would actually page you or leak data (auth, billing, webhook verification, permissions, or parsers).
  2. Run cargo mutants --file <path> (Rust) or npx stryker run --mutate <path> (JS/TS), or temporarily comment out one critical if guard by hand and run your test suite.
  3. Every time the suite stays green with a guard deleted, write the missing negative/boundary test until deleting the guard turns the suite red.

You will learn more about the real strength of your test suite in twenty minutes than a year of staring at coverage badges.

Frequently asked questions

What is mutation testing in simple terms? Mutation testing intentionally injects tiny, realistic bugs (called “mutants”) into your source code—like flipping > to >=, deleting an auth check, or returning early—and re-runs your test suite. If a test fails, the mutant is “killed” (good). If all tests still pass, the mutant “survived” and exposed a blind spot in your tests.

How is mutation testing different from code coverage? Code coverage only proves a line of code executed during tests—it does not prove any assertion checked the outcome. A test that calls an authorization function without asserting 403 Forbidden can give 100% line coverage while catching zero real regressions. Mutation testing measures whether your assertions actually enforce behavior.

Is mutation testing too slow to run in CI on every commit? Running full-repo mutation testing on every commit is usually too slow for large codebases. The practical approach is running targeted mutation testing on high-risk modules (auth, billing, parsers, security boundaries) or diff-only mutants in PRs, plus a full nightly sweep.

Related reading