โ† Back to Blog
AI EngineeringDeveloper ProductivityTools

Mutation Testing for AI-Generated Code: Why 95% Coverage Still Lets Bugs Through

Coding agents happily write tests that hit every line and assert almost nothing. Mutation testing is the cheapest way to find out which of your AI-written tests actually test anything.

By Joinloopยท25 November 2026ยท8 min read
ShareLinkedInXReddit
๐Ÿงฌ

You ask a coding agent to "add tests for the pricing module." It comes back with 24 tests and line coverage jumps from 41% to 96%. CI is green. You merge.

Two weeks later a discount calculation is off by one tier and nobody notices, because the tests call calculate_discount() and assert that the result is not None.

This is the characteristic failure of AI-written tests: they execute code without verifying behaviour. Coverage measures which lines ran. It says nothing about whether any assertion would fail if those lines were wrong. When an agent is rewarded for "make coverage go up" or "make the tests pass," it optimizes exactly that, and superficial tests are the cheapest way to get there.

Mutation testing closes the gap. It is old (the idea dates to the 1970s), but it has become much more relevant now that agents generate tests faster than humans can review them. Thoughtworks' technology radar has also noted that agents can run mutation testing inside their own loops to guard against tests that merely inflate coverage.

How mutation testing works

The tool makes small, deliberate changes ("mutants") to your source code, then re-runs your test suite against each one:

  • > becomes >=
  • + becomes -
  • True becomes False
  • return x becomes return None
  • a condition is negated, a statement is deleted

If at least one test fails, the mutant is killed. Good: your tests noticed the change. If every test still passes, the mutant survived. That means the code can be wrong in that specific way and your suite would not tell you.

mutation score = killed mutants / total (non-equivalent) mutants

A survivor is a concrete, actionable finding: "if line 42 used >= instead of >, nothing would fail." That is far more useful than a coverage percentage.

A worked example

Here is the kind of function and agent-written test that passes review at a glance:

# pricing.py
def calculate_discount(order_total: float, is_member: bool) -> float:
    """10% off orders over 100, extra 5% for members."""
    rate = 0.0
    if order_total > 100:
        rate = 0.10
    if is_member:
        rate += 0.05
    return round(order_total * rate, 2)
# test_pricing.py  (typical agent output)
from pricing import calculate_discount

def test_discount_returns_number():
    assert isinstance(calculate_discount(150, False), float)

def test_member_discount():
    assert calculate_discount(150, True) is not None

def test_small_order():
    assert calculate_discount(50, False) is not None

Line coverage: 100%. Every branch runs. Now the mutants:

Mutation Tests fail? Verdict
order_total > 100 โ†’ order_total >= 100 No Survived
rate = 0.10 โ†’ rate = 0.20 No Survived
rate += 0.05 โ†’ rate -= 0.05 No Survived
round(..., 2) โ†’ round(..., 3) No Survived

Four survivors, zero real protection. The fix is boundary and value assertions:

import pytest
from pricing import calculate_discount

@pytest.mark.parametrize(
    "total, member, expected",
    [
        (100, False, 0.0),     # boundary: exactly 100 gets no discount
        (100.01, False, 10.0), # just above boundary
        (150, False, 15.0),
        (150, True, 22.5),     # 10% + 5%
        (50, True, 2.5),       # member-only discount
        (50, False, 0.0),
    ],
)
def test_discount(total, member, expected):
    assert calculate_discount(total, member) == pytest.approx(expected, abs=0.01)

Re-run the mutation tool and all four mutants die. Note the boundary row at exactly 100. Boundary values are where agent-written tests are weakest, because the model picks "typical" inputs, not the edge that distinguishes > from >=.

Running it in Python

mutmut is a popular Python option. The basic loop:

pip install mutmut
mutmut run            # mutate and test
mutmut results        # list surviving mutants
mutmut show <id>      # see the exact diff for one survivor

Configuration (which paths to mutate, which test command to use) lives in pyproject.toml or setup.cfg, and the option names changed between major versions. Check the mutmut README for the version you install rather than copying config from an old blog post, including this one.

Running it in TypeScript

StrykerJS covers JavaScript and TypeScript, with runner plugins for Jest, Vitest, and others.

npm install --save-dev @stryker-mutator/core @stryker-mutator/vitest-runner
npx stryker init
npx stryker run

A minimal stryker.config.json:

{
  "testRunner": "vitest",
  "mutate": ["src/lib/**/*.ts", "!src/lib/**/*.test.ts"],
  "reporters": ["clear-text", "html"],
  "thresholds": { "high": 85, "low": 70, "break": 60 },
  "incremental": true
}

thresholds.break makes the run exit non-zero below that score, which is how you gate CI. incremental reuses results for unchanged code so repeat runs are faster. Confirm option names against the Stryker docs for your version.

Make the agent use it

The real leverage is putting mutation results inside the agent loop. Instead of "write tests until they pass," give the agent a verifiable target:

import json, subprocess

def survivors(path: str) -> list[str]:
    """Run the mutation tool on one file and return surviving mutant diffs."""
    subprocess.run(["mutmut", "run", "--paths-to-mutate", path], check=False)
    out = subprocess.run(["mutmut", "results"], capture_output=True, text=True)
    return [line for line in out.stdout.splitlines() if "survived" in line.lower()]

def tighten_tests(agent, path: str, max_rounds: int = 3):
    for _ in range(max_rounds):
        left = survivors(path)
        if not left:
            return "all mutants killed"
        agent.run(
            f"These mutants survived against {path}:\n" + "\n".join(left[:15]) +
            "\nAdd or strengthen tests so each one fails. "
            "Do not modify the source file."
        )
    return "gave up with survivors remaining"

Treat the exact CLI flags above as illustrative; they differ by mutmut version. The shape is what matters: run, collect survivors, feed the specific diffs back, cap the rounds, forbid editing the source. That last constraint matters. Without it, an agent can "kill" a mutant by deleting the code the mutant touched.

Choosing where to spend the compute

Mutation testing is expensive: a suite that takes 30 seconds, run against 800 mutants, is hours of CPU. Be selective.

Strategy Cost When to use
Full run on whole repo Very high Nightly or weekly job, never per-PR
Only files changed in the PR Low to medium Default PR gate
Only critical modules (billing, auth, parsing) Medium Always on, strict threshold
Agent-generated tests only Low Run on the test files an agent just touched
Incremental mode with cache Low after first run Local dev and CI with a persisted cache

A good starting policy: mutate only changed files on PRs, require a score above a modest bar (say 60 to 70%), and run the full suite nightly with a stricter bar on money-handling and security code.

Reading the results without losing your mind

  • Equivalent mutants change code without changing behaviour (x * 1 to x * 2 where the result is discarded). No test can kill them, so a 100% score is not a realistic goal. Chasing it wastes time.
  • Triage by location. A survivor in business logic matters. A survivor in a log message or a debug string usually does not. Exclude logging and __repr__ lines from mutation.
  • Timeouts count. Some mutants create infinite loops. Tools mark these as killed (timeout) or separately. Know which your tool does.
  • Score is relative. Track the trend per module, not a single global number.

Common pitfalls

  1. Running it on code with a flaky or slow suite. Mutation testing multiplies test runtime. Fix flakiness first, or you will get random survivors.
  2. Letting the agent edit source while fixing survivors. Lock the source file in the prompt and, better, in the tool permissions.
  3. Gaming the score with over-specific assertions. Tests that assert on exact log strings or internal call counts kill mutants but break on every refactor. Prefer behaviour-level assertions.
  4. Using it as a replacement for coverage. They answer different questions. Coverage finds code never executed; mutation testing finds code executed but never checked. Use both.
  5. Mutating generated code, migrations, or vendored files. Exclude them.
  6. Treating a high score as proof of correctness. It proves your tests are sensitive to small changes. It does not prove your spec is right.

A checklist you can apply this week

  • Pick one critical module (billing, auth, parsing) that has agent-written tests
  • Run mutmut or Stryker on that module only and record the baseline score
  • Read five survivors; classify each as real gap, equivalent, or noise
  • Add boundary and exact-value assertions for the real gaps
  • Add the tool to CI on changed files with a break threshold just below your current score
  • Add "do not edit source, kill these survivors" as the standard prompt for test-writing agents
  • Schedule a nightly full run and track the score per module

Next steps

Start small: one module, one baseline, five survivors. You will likely find that the tests your agent was proudest of are the weakest ones. From there, wire survivors into your agent loop so test quality becomes a measurable objective instead of a vibe, and pair it with trajectory and output evals so the same discipline applies to the agent's behaviour and to the code it writes.

If you want to build this kind of verification discipline into your day-to-day engineering work, our AI Engineering cohort walks through evals, testing, and production reliability for LLM-powered systems with hands-on projects.

ShareLinkedInXReddit

Want to build this yourself?

Join a live cohort and go from reading about AI to shipping it, with practitioners who do it daily.