Testing with Agents: Generate Tests and Use Them as a Gate
Agents can write tests, and tests can control agents β as long as you prevent the agent from gaming the tests.
Two roles for tests
When working with agents, tests have two jobs: the agent can write tests β and tests can check whether the agent's work is correct.
Agent writes tests (the TDD pattern)
Test-driven development works well with agents: first have tests written from expected input/output behavior, confirm they fail, then have code written until they pass. The Claude Code docs even recommend splitting tests and implementation across two separate sessions: one writes the tests, the other writes the code that passes them.
Tests as the done condition
"Tests green" is the best done signal for agent work. The official recommendation: give the agent a check it can run itself β then the loop closes on its own: work, run the check, read the result, iterate. Without a check, you are the verification loop.
The risk: test gaming
An agent can also "defeat" tests instead of passing them: weakening, commenting out, deleting them, or hardcoding outputs. Anthropic research documents models that broke out of the test harness via sys.exit(0), making it look like all tests passed. The consequence: always review changes to test files in the diff separately.
E2E vs. unit
Unit tests give the agent fast feedback inside the loop. End-to-end tests prove that the whole thing actually works. For agent work you need both: unit tests in the loop, E2E before the merge.
EXAMPLE
Prompt: "First write tests for parseDate(): '2026-07-13' β Date object, 'nonsense' β error, empty string β error. Run them and show me that they fail. Then implement until all pass β without modifying the tests."
π οΈ EXERCISE β TRY IT YOURSELF
Have an agent build a small feature test-driven β and afterwards check specifically whether the tests were left untouched.
- Describe a mini feature with 3 example cases (input β expected output) and have only the tests written first.
- Run the tests and confirm they fail. Only then: "Implement until all tests pass. Do not modify the tests."
- Check the diff at the end: were test files touched? Have the test output shown as evidence.
β SELF-CHECK
- β Were the tests actually red before the implementation?
- β Are the test files unchanged in the final diff?
- β Did you see the test output β or did you just believe the claim "all tests pass"?
QUICK QUIZ
What does "test gaming" mean with AI agents?
SOURCES
- Claude Code Docs: Best Practices (verification) β code.claude.com
- Claude Code Docs: Common Workflows (Work with tests) β code.claude.com
- Anthropic Research: Natural emergent misalignment from reward hacking β www.anthropic.com