Skip to main content

TDD & Testing with AI

Learning objectives
  • Run a test-first loop in which humans own the tests and the agent owns the implementation
  • Recognise and prevent the test-oracle problem in AI-written tests
  • Pick oracle-independent techniques (invariants, fuzzing, mutation, golden files, contracts, real databases, race tests) for a given risk
  • Write property-based and concurrency tests for ledger and inventory invariants in Go
  • Review AI-written tests, and explain why coverage is not evidence of quality

TL;DR​

  • Tests are the agent's feedback loop (it iterates until green) and your safety net (they define "done"). Whoever writes them defines correctness — so you write or approve them.
  • TDD with agents: approve failing tests from the spec, commit them red, then let the agent implement with tests locked by instruction, hook and review rule. An agent that can edit tests will sometimes pass them that way.
  • Test-oracle problem: tests derived from the implementation assert whatever the code does, bugs included. Expected values come from the spec, a hand calculation or an invariant.
  • Prefer oracle-independent checks: invariants (rapid), differential fuzzing, mutation testing, reviewed golden files, contract tests, real Postgres/Redis, -race stress tests.
  • Characterize legacy code before an agent refactors it. Coverage measures execution, not verification — never make it the agent's target.

Why it matters​

A coding agent loops: edit, run tests, read the failure, edit again. It optimises for what the tests check — nothing else. A weak suite yields code that is green and wrong; an editable suite offers a shortcut to green.

The failures that matter are invariant violations: a refund above the captured amount, an unbalanced journal entry, an overdraft without a facility, 500 units sold of a flash-sale item with 100 in stock. Tests written by the agent that wrote the code share its blind spots. The test portfolio itself is on Testing Strategy; this page covers what changes when an agent writes the code and some of the tests.

Core concepts​

Tests as the agent's feedback loop​

The loop is trustworthy only if it is fast and deterministic (flaky tests teach the agent to add sleeps and retries), actionable (refund 150000 exceeds captured 100000, not assertion failed), and separately owned: a human, or a session that sees only the spec, owns the tests.

TDD with an agent: the protocol​

  1. Spec first, with explicit edge cases: zero, exact limit, limit + 1, duplicate request, concurrent calls (see Requirements → Spec → Plan with AI).
  2. Tests from the spec — yours, or drafted by an agent in a session that sees the spec and interface but no implementation. Check every expected value by hand.
  3. Run red. Each test fails for the expected reason; one that passes already tests nothing.
  4. Commit red on its own: test(refund): acceptance tests for partial refunds. That commit is the contract.
  5. Lock and implement until go test -race is green. If a test looks wrong, the agent stops and explains; a human changes it in a separate commit.
  6. Review: git diff <red-commit>..HEAD -- '*_test.go' should be empty.

Instructions alone are probabilistic, so enforce the lock in layers:

  • Instruction in AGENTS.md / CLAUDE.md (templates: templates/ai-workflow/AGENTS.md, templates/ai-workflow/CLAUDE.md): "When tests are locked, never modify *_test.go or testdata/; if a test seems wrong, stop and explain."
  • Hook: templates/ai-workflow/dot-claude/hooks/protect-paths.sh is a Claude Code PreToolUse hook that blocks edits to *_test.go while .claude/tests.lock exists (exit 2 blocks the call — as of 2026, check current docs; see Setting Up a Repo for AI Agents). Extend it to testdata/ for golden files. It cannot see sed -i in the shell, hence the next layer.
  • Review and CI rule: test changes after the red commit need explicit reviewer sign-off; CODEOWNERS routes testdata/ and contracts to the domain owner; CI flags skipped or deleted tests.
# CI step: skipped or deleted tests need a test owner's approval.
diff=$(git diff origin/main...HEAD -- '*_test.go')
names() { grep -oE "^$1func (Test|Fuzz)[A-Za-z0-9_]*" <<<"$diff" | cut -c7- | sort -u; }
skips=$(grep -cE '^\+.*t\.Skip(f|Now)?\(' <<<"$diff" || true)
removed=$(comm -23 <(names '-') <(names '\+') | wc -l)
if ((skips > 0 || removed > 0)); then
echo "PR adds $skips t.Skip calls and removes $removed tests: needs test-owner approval"
exit 1
fi

The test-oracle problem​

Every test needs an oracle: an independent source of the expected answer. An agent writing tests alongside the code usually uses the code as its oracle — it predicts the output and asserts it. The suite encodes today's behaviour, bugs included, and passes on day one.

Spec: fee is 1.1% of the amount, rounded half-up to the đồng, minimum 1,000 VND, maximum 50,000 VND.

// Mirror test: reuses the implementation's arithmetic, so a truncating
// Fee passes. It never touches rounding or the clamps.
func TestFee_Mirror(t *testing.T) {
amount := int64(1_234_567)
want := amount * 11 / 1000
if got := Fee(amount); got != want {
t.Fatalf("Fee(%d) = %d, want %d", amount, got, want)
}
}

// Spec-derived test: expected values worked out by hand from the rule.
func TestFee_Spec(t *testing.T) {
tests := []struct {
name string
amount int64
want int64
}{
{"rounds half up", 1_234_591, 13_581}, // 13,580.501
{"exact half rounds up", 1_234_500, 13_580}, // 13,579.5
{"minimum applies", 50_000, 1_000}, // 550 -> 1,000
{"maximum applies", 10_000_000, 50_000}, // 110,000 -> 50,000
{"just under maximum", 4_500_000, 49_500},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Fee(tt.amount); got != tt.want {
t.Errorf("Fee(%d) = %d, want %d", tt.amount, got, tt.want)
}
})
}
}

Signs of oracle leakage in a PR:

  • Expected values computed with production helpers or the same formula (want := calc(x)), or precise literals nobody could derive by hand — output pasted from a run.
  • Assertions only on err == nil, len(got) > 0 or mock call sequences that restate the implementation.
  • Assertions weakened in the same commit as the behaviour change: tolerance widened, case deleted, t.Skip added, want set to got.
  • Only mid-range happy paths; no boundaries, no documented errors.

Prevention: derive expectations from the spec with the arithmetic in a comment; separate test-writing and implementing sessions; prefer invariants; run mutation testing on the changed package; and for risky tests, introduce the bug you fear and confirm a failure.

Oracle-independent techniques​

TechniqueOracle comes fromGo tooling (as of 2026)Best for
Property / state-machineA rule that always holdspgregory.net/rapid, testing/quickLedgers, allocation, state machines
Fuzzing, differential"Never panic", round trips, a reference implementationgo test -fuzzParsers, AI rewrites of existing code
Mutation testingThe suite must fail when code changesGremlins, go-mutestingAuditing AI-written tests
Golden filesA human-reviewed snapshottestdata/*.golden plus an -update flagStatements, settlement files, payloads
Contract testsConsumers' recorded expectationsPact, schema-registry compatibilitySilent API or event changes
Real dependenciesThe real database's behaviourtestcontainers-goSQL, locks, transactions, Redis scripts
Race and stressRace detector plus a concurrency invariantgo test -race -count=NBalances, stock reservation
CharacterizationCurrent legacy behaviourGolden masterBefore AI refactors legacy code

Mechanics are on Testing Strategy and Testing & Benchmarking; below is the AI-specific use.

Ledger invariants as a state-machine test​

Two invariants from Double-Entry Ledger Design: every transaction's entries sum to zero, and an account without an overdraft facility never goes negative. rapid drives random posting sequences and checks both after every step — nothing to mirror.

package ledger_test

import (
"errors"
"testing"

"pgregory.net/rapid"

"example.com/bank/internal/ledger"
)

func TestLedger_Invariants(t *testing.T) {
rapid.Check(t, func(t *rapid.T) {
l := ledger.NewInMemory()
l.Open("bank-cash", ledger.Options{Internal: true}) // funding source
l.Open("cust-a", ledger.Options{})
l.Open("cust-od", ledger.Options{OverdraftLimit: 5_000_000})
accts := []ledger.AccountID{"bank-cash", "cust-a", "cust-od"}

t.Repeat(map[string]func(*rapid.T){
"transfer": func(t *rapid.T) {
from := rapid.SampledFrom(accts).Draw(t, "from")
to := rapid.SampledFrom(accts).Draw(t, "to")
amt := rapid.Int64Range(1, 20_000_000).Draw(t, "amount")
_, err := l.Post(ledger.Transfer(from, to, amt))
if err != nil && !errors.Is(err, ledger.ErrInsufficientFunds) &&
!errors.Is(err, ledger.ErrSameAccount) {
t.Fatalf("unexpected error: %v", err)
}
},
"": func(t *rapid.T) { // invariant check, runs around every action
for _, tx := range l.Transactions() {
var sum int64
for _, e := range tx.Entries {
sum += e.Amount // debits negative, credits positive
}
if sum != 0 {
t.Fatalf("tx %s entries sum to %d, want 0", tx.ID, sum)
}
}
if b := l.Balance("cust-a"); b < 0 {
t.Fatalf("non-overdraft account at %d", b)
}
if b := l.Balance("cust-od"); b < -5_000_000 {
t.Fatalf("overdraft limit exceeded: %d", b)
}
},
})
})
}

On failure, rapid shrinks the sequence to a minimal counterexample — an ideal failure message for the agent. The standard library's testing/quick suffices for one-line properties of pure functions, but it is frozen and does not shrink.

Differential fuzzing when AI rewrites code​

When an agent rewrites a function, the old version is a free oracle. Keep a copy in the test file and fuzz both:

func FuzzAllocate_MatchesLegacy(f *testing.F) {
f.Add(int64(100_000), uint8(3))
f.Fuzz(func(t *testing.T, total int64, n uint8) {
if total < 0 || n == 0 {
t.Skip()
}
got := Allocate(total, int(n))
want := legacyAllocate(total, int(n)) // copied from the pre-refactor commit
if !slices.Equal(got, want) {
t.Fatalf("Allocate(%d, %d) = %v, legacy %v", total, n, got, want)
}
})
}

Mutation testing as an audit of AI tests​

Run a mutation tool on the package the agent touched. Each surviving mutant is a review question — "if >= became > here, which test fails?" — and mirror tests leave boundary mutants alive. Gremlins (github.com/go-gremlins/gremlins, pre-1.0 as of 2026 — check current docs) runs as gremlins unleash ./internal/refund. Run it nightly or on demand for money packages; equivalent mutants make 100% unrealistic, so treat the score as a signal, not a gate.

Golden files the agent cannot bless​

Golden files suit large outputs — settlement files, statements, payloads — and are the easiest test to game: on a mismatch, an agent reruns with -update. Rules: agents never run -update; humans read golden diffs; CODEOWNERS on testdata/ for money outputs.

Real Postgres: the oversell test​

Agents default to mocks because they are quick to generate and always pass. A mocked repository cannot reproduce the bug that matters for inventory: two transactions reading the same stock row. Use a real database and assert the invariant under concurrency:

//go:build integration

func TestReserve_NeverOversells(t *testing.T) {
ctx := context.Background()
store := inventory.NewPostgresStore(newTestDB(t)) // container + real migrations
if err := store.SetStock(ctx, "SKU-FLASH", 100); err != nil {
t.Fatal(err)
}

var reserved atomic.Int64
var wg sync.WaitGroup
for i := range 500 {
wg.Add(1)
go func() {
defer wg.Done()
err := store.Reserve(ctx, "SKU-FLASH", fmt.Sprintf("order-%d", i), 1)
switch {
case err == nil:
reserved.Add(1)
case errors.Is(err, inventory.ErrOutOfStock):
default:
t.Errorf("reserve: %v", err)
}
}()
}
wg.Wait()

left, err := store.Available(ctx, "SKU-FLASH")
if err != nil {
t.Fatal(err)
}
if reserved.Load() != 100 || left != 0 {
t.Fatalf("reserved %d, left %d; want 100 and 0", reserved.Load(), left)
}
}

A read-then-write implementation fails; a conditional UPDATE ... WHERE available >= $2 passes (see Locking & Concurrency Control). Run with -race -count=20: the race detector catches in-process races (an unguarded cache map), the invariant catches database-level races. The same pattern against a Redis container covers Lua-script reservations from the Flash Sale System.

Characterization tests before AI refactors legacy code​

A 2,000-line ProcessSettlement with no tests is where agents are most tempting and most dangerous: they "clean up" undocumented behaviour — a rounding quirk, a fallback currency, the side-effect order reconciliation depends on. First run it over anonymized real-shaped inputs and store outputs as golden files, bugs included; lock them; then let the agent refactor in small steps, each green against the pin. Intended behaviour changes go in separate PRs (see Code Smells & Refactoring).

Why coverage % is not quality​

Coverage reports which lines ran. Ask an agent for 85% and you get tests that call every function and assert err == nil. Coverage cannot see missing assertions, missing cases (the line ran with one input, not the boundary) or wrong oracles — a mirror test fully covers a wrong formula. Use it to find untested code, never to prove code is tested.

Review checklist for AI-written tests​

  • Oracle: each expected value traces to the spec, a hand calculation or an invariant.
  • Red first: the test failed before the implementation existed.
  • Boundaries and errors: zero, exact limit, limit ± 1, empty, duplicate, currency mismatch; each documented error asserted with errors.Is.
  • Assertions: outputs and resulting state, not only err == nil or call counts.
  • Mocks: only at real boundaries (PSP, clock); the database is real for SQL logic.
  • Concurrency: money and stock paths have a concurrent test run with -race.
  • Contract untouched: no edits to locked tests, goldens or contracts after the red commit; no new t.Skip, wider tolerance or deleted case.
  • Determinism: no time.Now(), time.Sleep, map order or shared state.
  • Mutation spot-check: flip one comparison by hand — something must fail.

Trade-offs​

ApproachStrengthsWeaknessesChoose when
Human writes tests, agent implementsStrongest oracle; clear ownershipSlower; needs disciplineMoney, auth, ledger, pricing
Agent drafts tests from spec in a separate session; human approvesFast; independent of the implementationAssertion review is mandatoryMost feature work
Agent writes code and tests togetherFastestOracle problem by defaultPrototypes, throwaway scripts
Property / state-machine testsNothing to mirror; shrinkingInvariants must be preciseLedgers, inventory, allocation

In practice​

An implementing-session prompt, kept in the repo's prompt library:

Implement partial refunds per docs/specs/refund-partial.md.
Tests in internal/refund/*_test.go are LOCKED (red commit a1b2c3d).
- Do not edit *_test.go or testdata/. If a test looks wrong, stop and explain.
- No new dependencies. Do not mock the database.
- Done = go test -race ./internal/refund/... and
go test -tags=integration -race ./internal/refund/... both green.
Report: files changed, any test you believe is wrong, and why.
touch .claude/tests.lock # arms the hook
go test -race -shuffle=on ./internal/refund/...
go test -tags=integration -race -count=20 -run NeverOversells ./internal/inventory/...
go test -fuzz=FuzzAllocate_MatchesLegacy -fuzztime=60s ./internal/money
git diff a1b2c3d..HEAD --stat -- '*_test.go' '*/testdata/*' # must be empty
rm .claude/tests.lock

CI runs go test -race on every PR (templates/ai-workflow/dot-github/workflows/ci.yml). Keep it fast; the agent runs it constantly.

Common pitfalls​

  • Letting the agent "fix" failing tests. Symptom: want values change in the same commit as the logic; a bug ships on green CI.
  • Tests generated from the code. Symptom: 90% coverage, no boundaries; the first incident is a boundary.
  • Mocked repositories for concurrency-sensitive code. Symptom: oversell in the first flash sale despite a green suite.
  • "Pure refactor" of legacy code without a pin. Symptom: rounding changes; reconciliation breaks at month-end.

Interview angle​

  • Prompts: "How do you make sure AI-generated code is correct?", "Would you let AI write your tests?"
  • A strong answer: tests are the spec and the feedback loop; humans own the oracle; locks enforced by tooling; invariants for money; real-database concurrency tests for stock; mutation testing to audit tests; characterization before refactors; coverage as a smell detector only.
  • Follow-ups: "What if the agent insists a test is wrong?" (it stops and explains; a human decides). "Isn't this slower?" (effort moves earlier; review gets faster because the contract is explicit).
  • Red flags: "the AI's tests pass, so it's fine"; coverage as proof; no concurrency tests for balances or stock.

Self-check​

1. Why must the implementing agent not edit tests, and how do you enforce it?

The agent optimises for green; if tests are editable, weakening an assertion is a valid path to green and the tests stop being an independent contract. Enforce with an AGENTS.md instruction, a pre-tool hook blocking edits to *_test.go and testdata/ while locked, and a review rule that the diff of test files since the red commit is empty unless a human approved it.

2. What is the test-oracle problem, and how does it show up in an AI-written PR?

AI tests written from the implementation use it as the oracle, so they assert current behaviour, bugs included. Signs: expectations computed with production helpers, literals pasted from a run, assertions only on err == nil, mock-sequence tests, no boundaries, assertions changed alongside the behaviour.

3. Why do property-based tests resist the oracle problem? Give two ledger invariants.

They assert a rule over all generated inputs instead of a computed expected value, so there is nothing to copy from the code. Ledger examples: each transaction's entries sum to zero; a non-overdraft account never goes below zero (and an overdraft account never below its limit).

4. Scenario: an agent rewrote Allocate for performance and all existing tests pass. What else do you require?

A differential fuzz test against a copy of the pre-refactor version, plus the allocation invariant (parts sum to the total, none negative). Existing tests cover only the cases someone thought of; the legacy version is a complete oracle for "behaviour unchanged".

5. Scenario: flash-sale reservation code arrives with 92% coverage, all tests on a mocked repository. What do you ask for before merge?

A testcontainers test on real Postgres (or Redis) firing hundreds of concurrent reservations at limited stock, asserting exactly N succeed and stock ends at zero, run with -race -count=N — plus an atomic conditional update or lock in the code. Coverage on mocks says nothing about database-level races.

🧠 Flashcards0/8 learned · 0 retries

Exercise​

TDD a "reserve stock" feature with your coding agent:

  1. Spec Reserve(ctx, sku, orderID, qty): idempotent on orderID, ErrOutOfStock when insufficient, never oversells.
  2. In a fresh session given only the spec and interface, have the agent draft tests. Review every assertion; add the concurrency test above and a rapid test (reserved + available always equals initial stock).
  3. Commit red, install templates/ai-workflow/dot-claude/hooks/protect-paths.sh and touch .claude/tests.lock.
  4. Have a separate session implement it; note whether it tries to edit a test.
  5. Run Gremlins on the package and add tests for meaningful survivors.

Done when: the red tests are unchanged in the final diff, the concurrency test passes 20 -race runs, and a deliberately introduced read-then-write bug is caught.

Further reading​

  • Michael Feathers, Working Effectively with Legacy Code (2004) — characterization tests.
  • Earl T. Barr, Mark Harman, Phil McMinn, Muzammil Shahbaz, Shin Yoo, "The Oracle Problem in Software Testing: A Survey" (IEEE Transactions on Software Engineering, 2015).
  • Go fuzzing documentation
  • pgregory.net/rapid package documentation (pkg.go.dev) — generators, shrinking, state-machine tests with T.Repeat.
  • Gremlins, mutation testing for Go (GitHub: go-gremlins/gremlins).
  • Claude Code documentation: Hooks
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).