Test-driven development suits AI agents better than it ever suited people. An agent needs a signal that says done or not done, and a failing test is exactly that. Claude Code's own best practices put it first: give the agent a check it can run.
The usual advice has a trap, though. Ask an agent to "take a TDD approach" and it writes the tests, then the code. Both come from the same understanding of the task. If the agent misunderstood the task, the tests and the code are wrong in the same way, and they agree. Everything is green.
Tests come from the request, not the code
The tests are where your intent lives, so they should come from you, or at least from your examples:
- Write the examples first. Three to five inputs with the exact output you expect, plus the edges: empty, zero, too long, missing. These are decisions, and they are yours.
- Turn them into tests. Write them yourself, or ask the agent to turn your examples into tests and nothing else. Read every assertion; each should match an example you wrote.
- Watch them fail. Run the tests before any code exists. A test that passes now checks nothing, and an agent will happily build on it.
- Commit the tests, and tag the commit with
git tag tests-locked. Now they are a fixed point to compare against. - Then let the agent implement, with one rule: the test files do not change.
Lock the tests
"Do not modify the tests" is an instruction, and instructions are advice. An agent stuck on a failing test will sometimes loosen an assertion, skip the test or change the expected value, then report success. Its summary may not mention it.
So check every time, against the tag from step 4:
git diff --stat tests-locked -- '*.test.*' tests/If that prints anything, the agent changed a requirement. Read that part of the change first.
Then try to break it
Passing your tests means the code does what your examples say. It does not mean your examples were enough. Two quick checks:
- Break the code on purpose. Flip a comparison or return a constant, and confirm a test fails. If none does, you were missing an example.
- Run [mutation testing](/haunt/mutation-testing-ai-tests/) on the module once the suite is too big to break by hand.
When the agent should write the tests
For code that already works, such as an old module you are about to refactor, letting an agent write characterisation tests is fine. They record what the code does today, so you notice when the refactor changes it. That is useful, and it is the opposite of test-driven development: those tests protect today's behaviour, bugs included. Can AI write your unit tests? covers that case.
Chapter 3 of the free book Checked, Not Trusted walks through writing your tests first from a request, with a lab where a quick fix passes the obvious test and fails at the edge.