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