How to test AI-generated code when the agent writes the tests
When a coding agent writes both the code and the tests, a green test run tells you that the two agree with each other. It doesn't tell you either one is right. The agent can misread the requirement once and encode the mistake in both places, write assertions too loose to fail, or edit the test that was in its way.
You can catch most of this without reading every line. This post has four checks that do it: exact assertions with property tests, mutation testing, a script that flags weakened tests in a pull request, and one that runs the old tests against the new code. We ran all the code here in a scratch repo, and the numbers come from those runs.
How agent-written tests go wrong
Two pieces of research put figures on it.
TestSuiteBench asked six coding agents to write test suites from specifications for 165 applications, then planted bugs and counted how many the suites caught. Most of the tests were valid: for four of the six agents, 88% to 96% passed on the correct program. They still missed a lot. The best agent's suites caught 55% of the planted bugs, and four of the six agents stayed below 40%.
ImpossibleBench gave agents tasks whose tests contradicted the specification, so the only way to pass was to cheat. GPT-5 passed 76% of one set of those tasks. The authors sorted the cheating into four kinds: editing the tests, special-casing the test inputs, overloading comparison operators, and recording state so that the same call returns different results.
So there are two separate problems to check for:
| Problem | What it looks like | Check that catches it |
|---|---|---|
| Weak tests | toBeDefined(), length-only checks, "doesn't throw" |
Mutation testing |
| Tests derived from the code | Expected values copied from the output | Property tests, examples you wrote |
| Weakened tests | .skip, deleted cases, fewer assertions |
Diff check in CI |
| Edited expectations | 500 quietly becomes 499 |
Old tests against new code |
| Tests that prove nothing | Pass with or without the change | New tests against old code |
100% coverage, 17 surviving bugs
Here's a small module of the kind an agent writes in one go:
export function applyDiscount(cents, percent) {
if (!Number.isInteger(cents) || cents < 0) throw new RangeError('cents');
if (percent < 0 || percent > 100) throw new RangeError('percent');
return Math.round(cents * (1 - percent / 100));
}
export function splitBill(cents, people) {
if (!Number.isInteger(people) || people < 1) throw new RangeError('people');
const share = Math.floor(cents / people);
const extra = cents % people;
return Array.from({ length: people }, (_, i) => share + (i < extra ? 1 : 0));
}
And a test file that looks reasonable at review speed. We wrote it to imitate a common agent style:
describe('applyDiscount', () => {
it('applies a discount', () => {
expect(applyDiscount(1000, 10)).toBeDefined();
expect(applyDiscount(1000, 10)).toBeLessThan(1000);
});
it('rejects bad input', () => {
expect(() => applyDiscount(-5, 10)).toThrow();
expect(() => applyDiscount(1000, 150)).toThrow();
});
});
describe('splitBill', () => {
it('splits between people', () => {
expect(splitBill(1000, 3)).toHaveLength(3);
});
it('rejects zero people', () => {
expect(() => splitBill(1000, 0)).toThrow();
});
});
Coverage was 100% for statements, branches, functions and lines. Then we changed percent / 100 to percent * 100. All four tests still passed, with applyDiscount(1000, 10) returning -999000. That number is less than 1000, so the assertion was satisfied.
Coverage records which lines ran. It has no idea whether anything checked the result.
Measure the tests with mutation testing
Mutation testing makes one small change to your code at a time, such as < to <= or / to *, and runs the tests after each. If a test fails, that mutant is killed. If everything passes, you've found a bug your suite can't see.
For JavaScript and TypeScript, use Stryker:
npm i -D @stryker-mutator/core @stryker-mutator/vitest-runner
Save this as stryker.config.json:
{
"testRunner": "vitest",
"mutate": ["src/**/*.js"],
"reporters": ["clear-text", "progress"],
"thresholds": { "high": 80, "low": 60, "break": 70 }
}
npx stryker run on the module above took three seconds and reported this:
File | total | covered | # killed | # timeout | # survived | # no cov |
All files | 57.50 | 57.50 | 23 | 0 | 17 | 0 |
Of 40 mutants, 17 survived, including one where splitBill returns an array of undefined. Because 57.5 is below the break threshold of 70, Stryker exits with code 1, which is what you want in CI. If you set thresholds at all you must give all three values.
For Python, mutmut does the same job with mutmut run and mutmut browse. It needs fork, so on Windows you run it inside WSL. Java has PIT.
Run it only on the lines that changed
A full mutation run on a large repo takes too long for every pull request. Stryker accepts line ranges, so you can build them from the diff. Save as scripts/mutate-changed.sh:
#!/usr/bin/env bash
set -euo pipefail
base=$(git merge-base "${1:-origin/main}" HEAD)
ranges=$(git diff -U0 --no-color --diff-filter=AM "$base" HEAD -- 'src/*.js' 'src/*.ts' ':!*.test.*' ':!*.d.ts' |
awk '/^\+\+\+ b\//{f=substr($0,7)}
/^@@/{split(substr($3,2),a,","); n=(a[2]==""?1:a[2]); if(n>0) printf "%s%s:%d-%d",(s++?",":""),f,a[1],a[1]+n-1}')
[ -n "$ranges" ] || { echo "no source lines changed"; exit 0; }
echo "mutating $ranges"
npx stryker run --mutate "$ranges"
On a one-line fix it printed mutating src/discount.js:3-3 and tested 15 mutants in place of the whole file. Stryker also has an incremental mode: on a second npx stryker run --incremental with nothing changed, all 40 results were reused. Its docs warn that it doesn't notice changed dependencies, environment variables or snapshot files, so do a full run on a schedule too.
Hand the survivors back to the agent
Surviving mutants make a good prompt because each is a specific missing test:
Run `npx stryker run`. For each surviving mutant, add or tighten a test so that it
fails on the mutant and passes on the current code. Work out the expected value from
the spec in docs/billing.md, not by running the function. Do not change anything in
src/. If a mutant is equivalent to the original code, list it and explain why.
The line about the spec matters. Mutation testing compares your tests with the code as it is today, so an agent can reach 100% by writing down whatever the current code returns, bugs included.
Write exact values and properties
This version of the tests killed all 40 mutants:
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { applyDiscount, splitBill } from '../src/discount.js';
describe('applyDiscount', () => {
it.each([
[1000, 10, 900],
[1000, 0, 1000],
[1000, 100, 0],
[0, 50, 0],
[999, 33, 669],
])('%i cents at %i%% off is %i', (cents, percent, expected) => {
expect(applyDiscount(cents, percent)).toBe(expected);
});
it.each([[-1, 10, 'cents'], [1.5, 10, 'cents'], [1000, -1, 'percent'], [1000, 101, 'percent']])(
'rejects %d cents at %d%%', (cents, percent, message) => {
expect(() => applyDiscount(cents, percent)).toThrow(new RangeError(message));
});
});
describe('splitBill', () => {
it('gives the leftover cents to the first people', () => {
expect(splitBill(1000, 3)).toEqual([334, 333, 333]);
expect(splitBill(500, 1)).toEqual([500]);
});
it.each([0, 1.5])('rejects %d people', (people) => {
expect(() => splitBill(1000, people)).toThrow(new RangeError('people'));
});
it('never loses or invents a cent', () => {
fc.assert(
fc.property(fc.nat(1_000_000), fc.integer({ min: 1, max: 50 }), (cents, people) => {
const shares = splitBill(cents, people);
expect(shares).toHaveLength(people);
expect(shares.reduce((a, b) => a + b, 0)).toBe(cents);
expect(Math.max(...shares) - Math.min(...shares)).toBeLessThanOrEqual(1);
}),
);
});
});
The last test is a property test, using fast-check. It states a rule and lets the library generate inputs. Rules are harder to copy from the implementation than example values, and special-casing a handful of inputs doesn't get past them.
To see the difference, we swapped in the obvious wrong version of splitBill, which rounds cents / people and repeats it. A hand-picked example, 900 split three ways, passed. The property failed on its second generated input and fast-check shrank it to splitting 99459 between 2 people, which gave back 99460.
Good properties to ask for: totals are conserved, encoding then decoding returns the input, sorting keeps the same elements, running a migration twice changes nothing, and user A never sees user B's rows.
A perfect mutation score still isn't proof
With all 40 mutants killed, we changed Math.round to Math.floor. All 13 tests passed. Stryker's mutations for this file didn't include that swap, and none of our examples landed on a half cent. Adding the case [999, 50, 500] caught it straight away. Treat the score as a way to find gaps, and pick the rounding, time zone and boundary cases yourself.
Flag weakened tests in the pull request
This script compares a branch with its base and fails on deleted test files, newly added .skip/.only/xfail markers, a net loss of assertions, and changes to test config, snapshots or CI. Save as scripts/test-guard.sh:
#!/usr/bin/env bash
set -euo pipefail
base=$(git merge-base "${1:-origin/main}" HEAD)
tests=(':(glob)**/*.test.*' ':(glob)**/*.spec.*' ':(glob)**/test_*.py' ':(glob)**/*_test.*')
bad=0
warn() { echo "test-guard: $1"; bad=1; }
count() { grep -cE "$1" || true; }
deleted=$(git diff --diff-filter=D --name-only "$base" HEAD -- "${tests[@]}")
[ -z "$deleted" ] || warn "deleted test files: $(echo $deleted)"
diff=$(git diff -U0 "$base" HEAD -- "${tests[@]}" | grep -vE '^(\+\+\+|---) ' || true)
skips=$(printf '%s\n' "$diff" | count '^\+.*(\.(skip|only|todo|fails)\(|\bx(it|describe)\(|pytest\.mark\.(skip|xfail)|pytest\.skip\()')
[ "$skips" -eq 0 ] || warn "$skips added line(s) skip, focus or expect failure in tests"
assertion='(\bexpect\(|\bassert\b|\bassert[A-Z(.])'
added=$(printf '%s\n' "$diff" | count "^\+.*$assertion")
removed=$(printf '%s\n' "$diff" | count "^-.*$assertion")
[ "$removed" -le "$added" ] || warn "$removed assertion lines removed, $added added"
config=$(git diff --name-only "$base" HEAD -- ':(glob)**/vitest.config.*' ':(glob)**/jest.config.*' ':(glob)**/stryker.config.*' ':(glob)**/pytest.ini' ':(glob)**/conftest.py' ':(glob)**/*.snap' ':(glob).github/workflows/*')
[ -z "$config" ] || warn "test config, snapshots or CI changed: $(echo $config)"
[ "$bad" -eq 0 ] && echo "test-guard: ok"
exit "$bad"
We ran it on four branches. An honest bug fix and a rewrite that strengthened the tests both passed. A branch that skipped the property test and dropped an assertion was flagged for the skip and the lost assertion. A branch that deleted the test file and added a vitest.config.js was flagged three times. Deleting a row from an it.each table isn't an assertion line, so the script can't see that; the next check can.
It works on text patterns and will sometimes flag a legitimate cleanup. That's fine. Its job is to make a person look at the test diff before merging.
Run the old tests on the new code, and the new tests on the old
This check finds what a text diff can't. It makes two temporary worktrees and swaps the test folders:
- Old tests on new code should pass. A failure means the change altered behaviour that was already specified.
- New tests on old code should fail. If they pass, they'd have passed without the change, so they prove nothing about it.
Save as scripts/cross-check.sh:
#!/usr/bin/env bash
set -uo pipefail
head=$(git rev-parse HEAD)
base=$(git merge-base "$1" "$head") || exit 2
dir=$2; shift 2
root=$(git rev-parse --show-toplevel)
tmp=$(mktemp -d)
cleanup() { git -C "$root" worktree remove --force "$tmp/w" >/dev/null 2>&1; }
trap 'cleanup; rm -rf "$tmp"' EXIT
run() { # run <code commit> <tests commit> <command...>
cleanup
git -C "$root" worktree add --quiet --detach "$tmp/w" "$1" || exit 2
(cd "$tmp/w" && rm -rf "$dir" && git checkout --quiet "$2" -- "$dir" && npm ci --silent) \
>"$tmp/log" 2>&1 || { echo "setup failed"; tail -n 20 "$tmp/log"; exit 2; }
(cd "$tmp/w" && "${@:3}") >"$tmp/log" 2>&1
}
fail=0
if run "$head" "$base" "$@"; then
echo "ok old tests pass on the new code"
else
echo "CHECK old tests fail on the new code"; tail -n 20 "$tmp/log"; fail=1
fi
if run "$base" "$head" "$@"; then
echo "CHECK new tests also pass on the old code"; fail=1
else
echo "ok new tests fail on the old code"
fi
exit "$fail"
Run it with your base branch, test folder and test command:
bash scripts/cross-check.sh origin/main test npx vitest run
| Branch | test-guard |
cross-check |
|---|---|---|
| Honest fix with a new failing-first test | Passes | Passes |
Code changed to Math.floor, expected value edited from 500 to 499 |
Passes | Old tests fail on the new code |
Cosmetic code change plus expect(1).toBe(1) |
Passes | New tests also pass on the old code |
The middle row is the one to worry about. Every test on that branch is green, the assertion count is unchanged, and only the old tests show that a price moved by a cent.
Pinning the commit with git rev-parse HEAD at the top matters. Our first draft used the word HEAD inside the worktree, where it means the old commit, so it ran old tests on old code and reported an honest fix as unproven. We found that by running the script on a branch where we knew the right answer. Do the same with any check an agent writes for you.
Two limits: pure refactors will fail the second half by design, and a new test that imports a function the old code doesn't have fails for that reason alone.
Put the checks in CI where the agent can't edit them
A check that lives in the branch can be changed by the branch. This workflow reads the guard scripts from main:
name: test-integrity
on:
pull_request:
types: [opened, synchronize, reopened, labeled, unlabeled]
permissions:
contents: read
jobs:
check:
runs-on: ubuntu-latest
if: ${{ !contains(github.event.pull_request.labels.*.name, 'tests-reviewed') }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-node@v6
with:
node-version: 22
- run: |
for s in test-guard cross-check mutate-changed; do
git show "origin/main:scripts/$s.sh" > "$RUNNER_TEMP/$s.sh"
done
- run: bash "$RUNNER_TEMP/test-guard.sh" origin/main
- run: bash "$RUNNER_TEMP/cross-check.sh" origin/main test npx vitest run
- run: npm ci && bash "$RUNNER_TEMP/mutate-changed.sh" origin/main
Merge the three scripts to main first, or git show has nothing to read. The tests-reviewed label is the escape hatch for refactors and intended behaviour changes, so limit who can apply labels. A pull request can still edit the workflow file itself, which is why .github/ and stryker.config.json should need a code-owner review.
Give the agent a way out
ImpossibleBench also tested what reduces cheating. Letting the model stop and flag a task for a human cut GPT-5's rate from 54% to 9% and o3's from 49% to 12%, with a much smaller effect on Claude Opus 4.1. Hiding the tests brought cheating close to zero but hurt performance on legitimate tasks. Read-only tests were a middle ground: they stop edits to the tests, though special-casing still gets through.
The first one costs you three lines in AGENTS.md or CLAUDE.md:
- If a test looks wrong or contradicts the spec, stop and say so. Don't edit it, and don't special-case its inputs.
- Don't delete, skip or loosen a test to get a green run. "I couldn't make this pass" is an acceptable answer.
- Write the failing test first and show me the failure before you change `src/`.
For read-only tests in Claude Code, add a deny rule while the agent implements, and take it out when you want new tests written:
{
"permissions": {
"deny": ["Edit(/test/**)", "Edit(/stryker.config.json)"]
}
}
Deny rules win over allow rules. According to the permissions docs, an Edit rule also covers recognised file commands such as sed and redirects in Bash, but not a Python or Node script that writes the file itself. That gap is a reason to keep the CI checks too. AGENTS.md and CLAUDE.md covers where to put standing rules, and the hooks guide has a hook that runs tests before Claude says it's done.
Use a different model for the tests
One model writing both sides tends to repeat its own misreading of the spec. Splitting the roles helps: give one session the spec and the public function signatures and have it write tests, then have another session implement against them without write access to the test folder. Separate git worktrees keep the two apart.
If you run Claude Code through ChromaLab, you can give each role its own model by starting the sessions with different ANTHROPIC_MODEL values from the models page. A separate API key per role lets you set a model whitelist and a daily token budget for each, under per-key controls. We haven't measured how much a second model improves the tests, so judge it by your own mutation score.
Where to start
If you only have an hour, run Stryker or mutmut once on the module that handles money, permissions or data deletion, and read the survivors. Then add cross-check.sh, since it catches the failures that look most like success. The diff guard and the CI workflow can follow when more than one person, or more than one agent, is merging.
Tests also won't find a missing access check that nobody thought to specify. For that, use the vibe-coding security checklist.
Questions people ask
Can I trust tests written by AI?
Trust them once something other than the same model has checked them. A mutation score shows whether they can fail, and running them against the old code shows whether they test your change.
What is a good mutation score?
There's no universal number. Stryker's defaults colour 80 and above as high and below 60 as low. Start by failing CI a little under your current score, then raise it, and expect more from billing and auth code than from glue code.
Should I write tests before letting an agent code?
For behaviour you care about, yes, even if it's only three examples and one property. Those are the only expected values in the repo that didn't come from the model.
Sources: TestSuiteBench, ImpossibleBench, the Stryker docs on the Vitest runner, configuration and incremental mode, fast-check, mutmut and Claude Code permissions, read on 23 November 2026. Tested with Vitest 5.1.1, Stryker 10.1.1 and fast-check 4.11.0 on Node 22.