Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

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.

By Checked Beginner1 h6 steps
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
On 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.ts

Note 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.

Explain the module · Claude Code, Codex or Cursor
Read [PATH TO MODULE] and its callers. Do not write any code yet. List the public functions and, for each one: - inputs and outputs, including types and units (currency, time zone), - the distinct behaviours (branches) with an example input for each, - edge cases: empty inputs, zero, negative numbers, boundaries, missing fields, - anything that looks like a bug or an inconsistency. Do not fix it; just list it with the line number.

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

Write the tests · Claude Code, Codex or Cursor
Write unit tests for [PATH TO MODULE] in [TEST FILE PATH], using our existing test framework and style (look at [EXAMPLE TEST FILE] first). Rules: - Do not modify the module under test. If something cannot be tested without changing it, stop and tell me. - One behaviour per test, named after the behaviour ("applies 10% discount when quantity is 10 or more"). - Assert exact values, not just that something is defined or truthy. Assert error types and messages for failure paths. - Cover every behaviour and edge case from the list we agreed, including the boundary values on both sides. - Where current behaviour looks like a bug, still pin the current behaviour, and mark the test with a comment "CURRENT BEHAVIOUR, see issue [ISSUE NUMBER]". - No mocks for pure functions. Mock only I/O (network, database, clock), and freeze time where dates matter. Run the tests and the coverage command when done, and show me the uncovered lines that remain.

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.ts

With no config file, StrykerJS runs npm test as the test command. Its HTML report lists each surviving mutant and the line it changed.

Give the surviving mutants back to the agent:

Kill the survivors · Claude Code, Codex or Cursor
These mutants survived mutation testing on [MODULE]: [PASTE SURVIVING MUTANTS: file, line, original, mutated] For each one, either add or strengthen a test so that it fails on the mutant, or explain why the mutant is equivalent (behaves identically) and can be ignored. Do not change the module.

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, #813

The 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.

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
Back to top