Materials / Practices

Generating tests with AI: tests that catch bugs

An agent can write a hundred tests in an afternoon, and most of them may only confirm what the code already does, bugs included. This guide shows how to make generated tests check the requirement, how to filter them, and how to stop an agent from weakening the tests you have.

9 min read4 Nov 2026Ilia Poliakov

The trap: tests that confirm the bug

The quickest way to get tests from an agent is to point it at a function and say "cover this". It reads the code, works out what the code does, and writes tests that assert exactly that. Coverage goes up. The tests pass. And every bug the function had is now protected by a test that will fail the day someone fixes it.

A running example. A subscription service computes the next renewal date. The requirement says: a monthly plan renews on the same day of the month; when that day does not exist in the next month, it renews on the last day of that month. The code does this:

def next_renewal(current: date) -> date:
    return current + timedelta(days=30)

Ask an agent to cover it and you may get a test like assert next_renewal(date(2026, 1, 31)) == date(2026, 3, 2). It passes. It is also wrong: a customer who subscribed on 31 January should be billed on 28 February, and the test now insists they are billed on 2 March. The agent did its job as asked. The request was the problem.

The rule that follows: write tests from the requirement, and read the code only to learn its interface (names, arguments, return types), not its behavior.

Tests from the spec, before the code

When a feature has a written spec with numbered acceptance criteria (see spec-driven development), the agent has something better than the code to test against. The order matters:

  1. List the criteriaThe agent reads the spec and lists each acceptance criterion by its number. Anything ambiguous is a question for a person now, not a guess in a test.
  2. One test per criterionEach test names the criterion it checks, in its name or a comment, so a reader and a reviewer can trace it both ways.
  3. Run them before the implementationNew tests must fail on the code as it is. A test that passes before the feature exists checks nothing.
  4. Implement until greenThe agent writes the code until the new tests pass, without changing them.

For the renewal example the criteria and their tests might read:

# AC-1: a monthly plan renews on the same day of the next month.
# AC-2: when that day does not exist, it renews on the last day of the month.
# AC-3: renewal dates are computed in the customer's billing time zone.

def test_ac1_same_day_next_month():
    assert next_renewal(date(2026, 1, 15)) == date(2026, 2, 15)

def test_ac2_short_month_takes_last_day():
    assert next_renewal(date(2026, 1, 31)) == date(2026, 2, 28)

def test_ac2_leap_year():
    assert next_renewal(date(2028, 1, 31)) == date(2028, 2, 29)

def test_ac3_billing_time_zone():
    # 23:30 on 31 March in Los Angeles is already 1 April in UTC.
    paid_at = datetime(2026, 4, 1, 6, 30, tzinfo=timezone.utc)
    tz = ZoneInfo("America/Los_Angeles")
    assert renewal_after(paid_at, tz) == date(2026, 4, 30)

Every one of these fails on the 30-day version, which is the point: each failure is a requirement the code does not meet yet.

A filter for generated tests

Generated tests should be treated like any generated code: useful only after they pass checks. Meta published the clearest example of such a filter. Its TestGen-LLM tool uses models to improve existing human-written tests, and keeps a generated test only when it builds, passes reliably, and increases coverage. On Instagram's Reels and Stories products, 75% of its test cases built correctly, 57% passed reliably and 25% increased coverage; in Meta's Instagram and Facebook test-a-thons, engineers accepted 73% of its recommendations for production (Alshahwan et al., "Automated Unit Test Improvement using Large Language Models at Meta", arXiv 2402.09171).

The lesson is in the drop between the numbers: most raw output does not survive. A filter is what makes the remainder trustworthy. A practical version for a team:

CheckWhat it removes
Builds and runsInvented APIs, wrong imports, tests for functions that do not exist
Passes 5 to 10 runs in a row, in random orderFlaky tests that depend on the clock, test order, network or shared state
Adds coverage of lines or branchesDuplicates of tests you already have
Fails on at least one mutant (next section)Tests with weak or missing assertions
Names a requirementTests that lock in current behavior with no stated reason for it

The first three can run unattended in CI. The fourth is cheap on changed files. The fifth is a review rule: a test with no criterion behind it needs a sentence explaining why the behavior it pins is intended.

Mutation testing: checking the tests themselves

Coverage says a line ran during a test. It does not say anything checked the result. A test that calls next_renewal and asserts nothing covers the function completely.

Mutation testing measures the assertions instead. A tool makes small changes to the code, called mutants: < becomes <=, a constant changes, a call is removed, a condition is negated. It runs the tests against each mutant. If some test fails, the mutant is killed. If every test still passes, the mutant survived, and the code at that spot is effectively unchecked.

The common tools are Stryker (JavaScript and TypeScript, C#, Scala), PIT (Java and the JVM) and mutmut (Python). Running them across a whole codebase is slow, so run them on the files a pull request changed:

# setup.cfg: mutate only the module the pull request touched
[mutmut]
source_paths=src/
only_mutate=
    src/billing/renewal.py

# then, in CI or locally
mutmut run
mutmut browse   # inspect the mutants that survived

Surviving mutants make good agent tasks: "this mutant of line 42 survives; write a test, traced to a criterion, that kills it." The task is concrete, the result is checkable, and the agent cannot satisfy it with a test that asserts nothing.

Keeping the agent from weakening tests

An agent asked to make a failing build green has two options: fix the code or change the test. Without instructions it will sometimes take the second, loosening an assertion, adding a skip, or rewriting an expected value to match the wrong output. Defend in layers, because any one layer can be missed:

A minimal version of the CI check:

#!/bin/sh
# Flag edits to existing tests and new skips in this pull request.
base=${BASE_REF:-origin/main}
changed=$(git diff --name-only --diff-filter=MD "$base"...HEAD -- 'tests/' '**/*.test.*')
skips=$(git diff "$base"...HEAD -- 'tests/' '**/*.test.*' \
        | grep -E '^\+.*(\.skip|\.only|@pytest\.mark\.(skip|xfail))' || true)
if [ -n "$changed$skips" ]; then
  echo "Existing tests changed or skipped; a person must review:"
  echo "$changed"; echo "$skips"
  exit 1
fi

Old code without requirements

Legacy code often has no spec to test against, and the requirement lives in the code and in people's heads. Here tests of current behavior are the right tool, as long as everyone knows that is what they are. These are characterization tests:

  1. Record what the code doesThe agent writes tests of current behavior, marked as characterization tests in their names or a tag, so nobody mistakes them for requirements.
  2. Flag what looks wrongA person reads the recorded behavior and files each suspicious case, such as the 30-day renewal, as a separate task instead of silently accepting it.
  3. Refactor under the testsChanges that should not alter behavior keep the characterization tests green.
  4. Move toward requirementsAs each module gets a spec, its characterization tests are replaced by tests traced to criteria.

Where agents write good tests, and where they don't

QualityKind of test
GoodUnit tests of pure functions; boundary and table-driven tests (dates, amounts, limits); API contract tests generated from a schema; serialization and parsing round trips
Needs close controlIntegration tests with a database or queue; tests that need many mocks, where the agent can end up testing its own mocks
WeakEnd-to-end UI tests with no written scenario; load tests; tests that need product knowledge the repository does not hold

For the weaker kinds, give the agent the scenario in writing: who the user is, what they do, what they should see. The agent is good at turning a precise scenario into a test and poor at inventing the scenario.

Questions

Can we trust tests an agent generated?

Trust the ones that pass a filter: they build, pass repeatedly, add coverage, kill a mutant and name the requirement they check. Tests written by reading the code tend to lock in its bugs, so be most suspicious of those.

Coverage went up after we added generated tests. Did quality?

Not necessarily. Coverage shows that code ran, not that anything checked the result. Use mutation testing on changed files and watch the rate of defects that escape to QA and production.

What do we do when the agent edits tests to make them pass?

Forbid it in the agent's instructions, flag edits to existing tests and new skips in CI, make them blocking in review, and put critical tests under CODEOWNERS. Each layer catches what another misses.

Which tests should we generate first?

Unit tests for pure logic, boundary cases, contract tests from schemas and serialization tests. Integration and end-to-end tests need a written scenario and closer human control.