Workflow recipe
Write unit tests for legacy code with a coding agent
An agent writes characterisation tests, you check for weak assertions and prove them with mutation testing.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
To generate unit tests with AI for legacy code, measure the module’s coverage first, ask the agent to explain the code before it writes anything, and have it write characterisation tests under strict rules. Review the tests for weak assertions, run mutation testing to see whether they catch deliberate bugs, and record the before and after numbers.
Coding agents write tests quickly, and the coverage number goes up. The trap is that tests written by reading the code tend to assert whatever the code currently does, including its bugs, and often assert very little. This recipe uses the agent for what it does well and then checks the tests with mutation testing, which changes the code on purpose and sees whether any test notices.
The goal is characterisation tests: tests that pin down today’s behaviour so you can change the module safely later.
TerminalAbout 5 min
1. Pick the module and measure the baseline
Choose one module with real business logic, such as pricing, permissions or date handling. Record its current line and branch coverage.
npm install -D @vitest/coverage-v8
npx vitest run --coverage --coverage.include=src/billing/pricing.tspip install pytest-cov
python -m pytest --cov=billing.pricing --cov-branch --cov-report=term-missingNote the uncovered lines from the report. They are your target list.
Agent chatAbout 5 min
2. Ask the agent to read and explain before it writes
Make the agent describe the behaviour first. It is easier to spot a misunderstanding in a list than in 300 lines of tests.
Read the list and correct it. Anything flagged as a possible bug goes to a separate issue, not into this change.
Agent chatAbout 15 min
3. Generate characterisation tests with strict rules
EditorAbout 10 min
4. Review the tests for weak assertions
Read the generated tests before running anything else. Look for the patterns that make tests pass no matter what:
// Weak: passes for almost any return value
expect(result).toBeDefined();
expect(prices.length).toBeGreaterThan(0);
expect(fn).not.toThrow();
// Strong: fails if the behaviour changes
expect(result).toEqual({ subtotal: 100, discount: 10, total: 90 });
expect(() => priceFor(-1)).toThrow(new RangeError("quantity must be positive"));Also check for tests that re-implement the logic they are testing (computing the expected value with the same formula), and for snapshot tests of large objects that nobody will read when they change.
TerminalAbout 20 min
5. Run mutation testing on the module
A mutation tool makes small changes to the code (flips a > to >=, removes a line, changes a constant) and runs your tests. If no test fails, that mutant “survived”, which means your tests would not have caught that bug.
npm install -D @stryker-mutator/core
npx stryker run --mutate src/billing/pricing.tsWith no config file, StrykerJS runs npm test as the test command. Its HTML report lists each surviving mutant and the line it changed.
[tool.mutmut]
source_paths = ["billing/"]
pytest_add_cli_args_test_selection = ["tests/"]pip install mutmut
mutmut run
mutmut results # list surviving mutants
mutmut show billing.pricing.x_line_total__mutmut_11 # the diff for one of them
mutmut browse # or step through them interactivelymutmut 3 copies your code into a mutants/ folder and runs the tests there. Add mutants/ to .gitignore, and pass --ignore=mutants when you run pytest yourself, or pytest collects the copied tests twice and stops with an “import file mismatch” error.
Give the surviving mutants back to the agent:
Expect a few survivors to be equivalent mutants. In our re-run, the step 3 prompt in a fresh Claude Code session wrote 23 tests for the pricing function, took branch coverage from 60% to 100%, and pinned five behaviours as suspected bugs, among them a discount over 100% that makes the total negative and round() turning 2.675 into 2.67. Mutation testing then killed 25 of 26 mutants. The survivor changed if discount_pct > 0 to >= 0. A discount of 0% multiplies the total by 1, so no test can tell the two apart: that mutant is equivalent, and the pull request should list it with that one-line reason rather than a test written to kill it.
Pull requestAbout 5 min
6. Record before and after, and merge
Re-run coverage and mutation testing, and put both numbers in the pull request description:
Module: src/billing/pricing.ts
Line coverage: 41% -> 96%
Branch coverage: 30% -> 92%
Mutation score: 38% -> 87% (4 equivalent mutants ignored, listed below)
Suspected bugs pinned as CURRENT BEHAVIOUR: #812, #813The mutation score is the number that tells reviewers the tests are real.
Check it worked
Verification checklist
0 of 6 done
When it goes wrong
If the agent edits the module “to make it testable”, revert and repeat the rule. Refactoring for testability is a separate change with its own review.
If the tests are flaky, look for real clocks, random values and shared state between tests. Freeze time and seed randomness in the test setup.
If mutation testing takes too long, limit it to the one module (as above) and run it locally or nightly rather than on every push.
If the coverage tool reports nothing for the module, check the include path or module name; it must match how the test imports the file. If plain pytest fails with ModuleNotFoundError for your own package, run python -m pytest, which puts the current folder on the import path, or set pythonpath = ["."] in the pytest section of pyproject.toml.
If the mutation score is far lower than the coverage suggests, the tests run the code without checking it. When we re-ran steps 1, 3 and 5 on 25 November 2026 with mutmut 3.8.1, against a small pricing function and one test that only asserted the result is not None, 24 of 26 mutants survived. That is the pattern step 4 is there to catch.
Variations
For a module with no clear spec, ask the agent to write property-based tests (fast-check in TypeScript, Hypothesis in Python) for invariants such as “total never exceeds subtotal” alongside the example-based tests.
If you want the agent to work test-first on new behaviour afterwards, follow test-driven development with a coding agent, which adds hooks that stop the agent editing tests to make them pass. The test-driven-development skill packages the red-green-refactor routine on its own.
Once the module has tests, the same suite is the safety net for bigger changes: upgrade dependencies with AI runs it after each step of a major-version upgrade, and generate documentation from code with AI writes up the module with every statement checked against the source.
Related testing guides
For end-to-end coverage rather than unit tests, generate Playwright tests with AI. Reviewing AI-written code applies to tests as much as features, and your first Claude Code session covers the agent setup this recipe assumes. The AI for test engineers learning path includes this recipe, and more are in the AI workflow examples hub.
Outcome and tools
- Outcome
- Higher coverage on one module, with assertions that would catch real bugs.
- For
- Developers
- Variants for
- Claude Code, Codex, Cursor
Related
- Generate Playwright tests with AI agents, then review them
Approve a test plan before any code exists, generate tests from it and review them like production code.
- Test-driven development with a coding agent
Agree the seams, write one failing test, lock the tests with a hook while the agent makes it pass, then prove the test can fail.
- Write a useful AGENTS.md: example, template and test
An AGENTS.md example and template with build and test commands, conventions and traps, plus a before-and-after task that shows whether the file actually helps.
- Test automation
Automating functional, API and end-to-end checks so every change gets tested.
- Your first session with Claude Code
Install it, run it in a real repository, approve its first changes, commit a reviewed edit and learn the commands you will use daily.