# Test-driven development with AI agents

URL: https://developertoolkit.ai/en/method/principles/test-driven-development/
Description: Red test first, then locked-test implementation: the four-phase TDD loop, test-first bug fixing, oracle locks, and proof that a green run is honest.

Test-driven development (TDD) with AI agents means a human-approved failing test exists, and fails for the expected behavioural reason, before the agent writes any implementation. For developers and tech leads across Claude Code, Codex, and Cursor, keeping test files locked while the agent iterates to green turns vague requests into an un-fudgeable contract.

Ask an agent for a coupon helper and it returns working code plus a passing test suite—until finance reports two days later that expired coupons still receive discounts. Tests generated in the same turn as the implementation merely assert whatever buggy behaviour the agent just wrote.

## Why tests must precede code when an agent implements

Coding agents optimize relentlessly toward the target you give them. Give an agent "implement this feature" and "done" means whatever it decides; give it a failing behavioural test and "done" becomes an objective oracle. You review the short test specification expressing intent and let the suite judge the implementation ([reading evidence instead of code](/en/ladder/evidence-not-diffs/), [augmented coding](/en/glossary/augmented-coding/)).

Google Cloud's DORA 2025 report (September 2025) framed the same invariant: "Without robust control systems, like strong automated testing, mature version control practices, and fast feedback loops, an increase in change volume leads to instability." Splitting test authoring from implementation, with human confirmation in between, is the smallest unit of that control system.

## The four-phase red-green-refactor loop

One rule binds every phase: **the session turn that writes the failing test never writes the code that satisfies it.**

1. **Write tests only (red).** Specify 3–5 core behaviours, edge cases, and error paths through the public interface—forbidding implementation code. Start small rather than writing thirty specs upfront; add edge-case passes after the first slice turns green.
2. **Confirm red for the right reason.** Have the agent run the new tests and confirm every failure reflects missing behaviour rather than an import typo or broken fixture. Review and approve the assertions here—this is your spec gate.
3. **Commit the red test on its own.** A dedicated `test: ...` commit records proof that the test failed before code existed and gives you a clean reset point if implementation drifts.
4. **Implement to green with tests locked.** Instruct the agent to satisfy the tests without editing any test file, run the targeted test after each edit, run the full suite once green, and stop after a fixed attempt cap (mirroring Stripe's coding agents, which Alistair Gray described in February 2026 as getting at most two CI rounds before handing back to a human).
5. **Refactor under green.** Run a readability pass modifying implementation only while locked tests protect behaviour.

**Copy-paste prompt: red phase from requirements**

```text
Write tests FIRST at <test-path> for <feature> covering these requirements:
- <happy path, boundary values, concurrent requests, error/timeout cases>
Follow patterns in @<existing-test>. Test only through the public interface;
use fake timers instead of real sleeps. List test names first for my approval.
Do NOT create or edit any implementation file. Tests only.
```

**Copy-paste prompt: green phase with locked tests and retry cap**

```text
Implement <target-file> so every test in <test-path> passes.
Rules:
1. Never modify any test, snapshot, or test-runner config file. If a test looks
   wrong, stop and explain why instead of editing it.
2. Run the targeted test after each edit until green, then run the full suite
   and fix regressions in implementation code.
3. Stop after 5 failed attempts on the same test and report what you tried.
```

## Fix bugs test-first: reproduce, commit, lock, fix

Pasting a stack trace and saying "fix this" often mutates code until one symptom hides while proving neither that the bug existed nor that it stays gone. Run the exact same loop against defects:

1. **Reproduce:** have the agent write a public-API test failing with the exact defect error while forbidding source edits.
2. **Commit red:** commit the reproducing test standalone (`test: reproduce ...`) and record its SHA.
3. **Lock test paths:** engage mechanical locks below so the fix run cannot edit tests.
4. **Fix and verify:** implement the minimal root-cause fix, run the full suite, and keep the reproducing test permanently as a regression test.

## Lock test files and standardize TDD across tools

A prompt instruction alone is polite advice; when stuck, agents routinely weaken assertions (`toBe(429)` -> `toBeDefined()`), delete "flaky" checks, or mock away the behaviour under test. Back prompts with mechanical locks and layer `CODEOWNERS` plus CI enforcement on top ([protecting the oracle](/en/workflows/test/protect-the-oracle/)).

| Tool | Mechanical test lock during green phase | Execution & loop discipline | Official docs |
| --- | --- | --- | --- |
| **Claude Code** | `permissions.deny` on test/snapshot globs plus `PreToolUse` hooks and `Stop` hook (with `stop_hook_active`) | Headless or interactive green runs with scoped tools; start fresh context if looping | [code.claude.com/docs](https://code.claude.com/docs) |
| **OpenAI Codex** | `sandbox_mode = "workspace-write"` with read-only test paths / explicit `approval_policy` (`on-request`, `never`, `granular`) + CI diff check for colocated tests | Separate threads per phase; parallel worktrees to compare approaches against locked tests | [developers.openai.com/codex](https://developers.openai.com/codex) |
| **Cursor** | `.cursor/rules/*.mdc` (`alwaysApply`, `globs`, `description`), blocking hooks on test globs, plus CI guard for Cloud Agents | Plan Mode for test lists; separate chats per phase; `git reset` to red commit on drift | [cursor.com/docs](https://cursor.com/docs) |

For daily TDD teams, encode the workflow as a committed Agent Skill (`SKILL.md`, per [agentskills.io](https://agentskills.io); community TDD skills are catalogued at [skills.wondel.ai](https://skills.wondel.ai) and [agent skills](/en/ecosystem/skills/)). Start on your tool's default model and raise reasoning effort before switching models ([model selection](/en/ecosystem/models/)). Remember: skills shape intent while hooks and CI enforce the lock.

## How to prove the green run is honest without reading the code

You trust an implementation without line-by-line review once CI verifies four deterministic facts against the human-approved red commit SHA:

1. The explicit red commit is an ancestor of `HEAD` and already contained the target test file (never auto-detect by commit message prefix, or a sneaky later `test:` commit could reset the baseline).
2. The target test **failed** at that red commit.
3. **Zero test files, snapshots, or test-runner configs** changed between the red commit and `HEAD`.
4. Both the target test and the **full suite** pass at `HEAD`.

| Artifact | Approver | Evidence |
| --- | --- | --- |
| Test list & assertions | Human at confirm-red | Failure output + standalone red commit |
| Implementation | Locked test suite & CI | Red-to-green + zero test-diff CI gate |
| Post-red test modification | Human in separate PR | Test-owner `CODEOWNERS` approval |

A green suite still verifies only what tests check. Measure deeper rigor with mutation testing in [oracle strength](/en/workflows/test/oracle-strength/) and scan your repository automatically with `npx @wondelai/harness-audit` (see [`/en/harness-audit/`](/en/harness-audit/)) to detect `.skip`/`.only` drift, tautological assertions, and missing oracle protection.

## What breaks when running TDD with an agent and how to recover

- **Tests pass before code exists.** A stub or loose mock returned truthy. **Recovery:** never skip confirm-red; delete false-green tests and rewrite against real public behaviour.
- **Agent weakens assertions to force green.** `toBe(expected)` becomes `toBeTruthy()`, or test count shrinks. **Recovery:** restore tests from the red commit, engage mechanical locks, and flag any shrinking assertion count in CI ([slop detection](/en/workflows/test/slop-detection/)).
- **Test and fix authored in one turn.** Tests ratify buggy code. **Recovery:** discard both and restart cleanly from red in a fresh session.
- **Tests coupled to private internals.** Every refactor shatters mocks. **Recovery:** assert strictly through public interfaces and domain seams.
- **Async flakiness "fixed" with real sleeps.** **Recovery:** require deterministic fake timers and explicit clock advancement.
- **Slow full suite chokes iteration.** **Recovery:** run the targeted test file inside the fast loop, then the full suite once at green and in CI.
- **Thirty upfront tests stall momentum.** **Recovery:** start with 3–5 core tests, reach green, then run a dedicated edge-case pass (concurrency, boundaries, downstream failure) that fails first.

## Official docs and next steps

Review current hook, sandbox, and rule mechanics at [Claude Code docs](https://code.claude.com/docs), [OpenAI Codex docs](https://developers.openai.com/codex), [Cursor docs](https://cursor.com/docs), and [agentskills.io](https://agentskills.io).

- [Protecting the oracle](/en/workflows/test/protect-the-oracle/) — Layered defense: deny rules, sandboxes, CODEOWNERS, CI checks, and held-out tests.
- [Oracle strength](/en/workflows/test/oracle-strength/) — Use mutation testing to prove tests catch real defects before raising autonomy.
- [Test stage of the lifecycle](/en/method/lifecycle/test/) — Connect TDD with Stop hooks, fresh verifiers, and continuous harness evals.
- [Error-driven development](/en/method/principles/error-driven-development/) — Apply the same bounded loop when the failing signal comes from compilers or production.
