Test generation and TDD with Claude Code
PLTest generation and TDD with Claude Code succeed when tests operate as an uneditable contract: Claude mirrors existing test conventions, proves each test fails before coding, implements with test files locked, and receives automatic hook feedback on every edit. Mutation checks and CI then prove the suite catches real defects without manual line-by-line review.
A checkout endpoint passes every unit test with a 94% coverage badge and still throws 500s in production because nothing exercised the seam where payment capture succeeds and the database write fails. Every test asserted that mocks were called. This guide serves developers running Claude Code locally and tech leads enforcing trustworthy test discipline across branches.
Dividing verification so nobody grades their own homework
Section titled “Dividing verification so nobody grades their own homework”Approve observable behaviour rather than generated lines. Separate authoring, execution, and judgment so no generated artifact relies solely on the same model’s claim:
| Artifact | Producer | Verification | Sign-off |
|---|---|---|---|
| Behaviour list | Developer or Claude from spec | Review 10–20 test names before any code is written | Developer |
| Failing test (Red) | Claude (test-only scope) | Runs red for the expected assertion reason | Session output / hook |
| Implementation (Green) | Claude (test files locked) | Suite passes while git diff leaves test files untouched | CI |
| Oracle strength | Independent check or mutation runner | Planted defects must break the suite | Reviewer reads survivor table |
| Merge readiness | CI outside agent control | Typecheck, lint, full suite, changed-file coverage | Code owner reviews evidence bundle |
See executable acceptance criteria for how test cases enter this loop and the evidence bundle for what every PR carries.
Wire the automated test feedback loop once per repository
Section titled “Wire the automated test feedback loop once per repository”Claude produces far stronger tests when test commands live in CLAUDE.md and hook feedback returns failures automatically:
- Document single-file, related-file, and full-suite commands in
CLAUDE.md. Specify test co-location rules and state that tests are never edited to make failing code pass. - Attach a
PostToolUsehook onEdit|Writeto run tests related to the modified file. Exit code2sends stderr directly back to Claude so it fixes regressions on the next step; exit code1is ignored by Claude Code. - Attach a fast
Stophook that blocks completion when tests fail. Checkstop_hook_activeso a stubborn failure retries once and then escalates to a human instead of burning turns. Keep slow integration and E2E suites in CI so turns stay fast.
See Claude Code hooks automation for full hook wiring, JSON output contracts, and fixture tests, and check the official Claude Code documentation for current event schemas.
Run red-green-refactor with locked test files
Section titled “Run red-green-refactor with locked test files”A test that has never failed proves nothing. Worse, an agent asked to “make tests pass” will frequently weaken an assertion if it can edit the test file. Enforce separation across the loop:
-
Mirror existing conventions and approve behaviour names first. Have Claude inspect two strong existing test files and propose 10–20 one-line test names covering happy paths, thrown errors, and catch branches. Reviewing behaviour names takes one minute; reviewing 300 lines of generated tests takes ten.
-
Write the failing test in a test-only session. Restrict writes to test files (for example via
--allowedToolsscoped toEdit(src/**/*.test.ts)in non-interactive mode) so the red step cannot modify production code. -
Confirm it fails for the right assertion. Verify the failure reports the missing behaviour (such as a duplicate payment charge on a retried idempotency key) rather than a syntax error or missing import.
-
Implement with test files denied. Run the implementation session with test edits blocked (via
--disallowedTools "Edit(**/*.test.ts)"or aPreToolUsepath-protection hook) and instruct Claude to stop and explain if it believes a test is wrong. -
Verify the test diff stayed clean, then refactor under green hooks. Confirm
git diff --statexcludes test files (shell scripts can still bypass file-tool rules unless backed by OS sandboxing and CI checks), then refactor safely whilePostToolUsere-runs related tests after every edit.
For the team-scale CI and CODEOWNERS controls that stop agents from modifying test suites on pull requests, read protecting the oracle and test-driven development with AI.
Test seams and real DOMs, not mocks or fixed timers
Section titled “Test seams and real DOMs, not mocks or fixed timers”Two categories of generated tests regularly create false confidence:
- Over-mocked unit tests. Mock only true external boundaries (payment HTTP calls, third-party APIs, injected DB driver failures) and execute your real routing, validation, and serialization layers. Always explicitly name idempotency for any route with side effects—both humans and agents routinely omit it. Where integration tests target a real database, connect a read-only database MCP server so Claude inspects the real schema rather than guessing (MCP ecosystem).
- Flaky end-to-end tests. Never let an agent invent CSS selectors blindly. Give Claude a real browser via a browser MCP server (such as Playwright MCP; see Model Context Protocol) so it walks the live DOM, locates elements by accessible role or
data-testid, uses web-first assertions with zero fixedwaitForTimeoutcalls, wraps phases in named steps, and verifies stability across repeated runs before committing.
Proving generated tests actually catch bugs
Section titled “Proving generated tests actually catch bugs”Line coverage records executed lines, never whether assertions verified behaviour. Prove suite quality with four checks that avoid reading every generated line:
- Red-first proof. Confirm every new test failed before implementation.
- Repeat-run stability. Run new tests three times consecutively to catch race conditions and shared state immediately.
- Fresh-context test review. Ask a separate read-only subagent to state what behaviour each added test verifies and flag any test that would still pass if the implementation returned a constant.
- Mutation testing. Plant plausible bugs one at a time and verify the suite turns red, or run automated mutation testing (such as Stryker) in CI. Commit or stash your work before running an agent-driven mutation probe:
See oracle strength for mutation and flake thresholds before running unattended agent loops, and run npx @wondelai/harness-audit to audit your repository’s test-oracle safeguards (Harness Audit).
Packaging test standards and isolating CI triage
Section titled “Packaging test standards and isolating CI triage”Capture your team’s mandatory test checklist (stack, seam-mocking rules, idempotency case, red-first requirement) in a project Agent Skill at .claude/skills/test-route/SKILL.md with disable-model-invocation: true so every developer runs the exact same standard (custom commands and skills, Agent Skills, and skills.wondel.ai).
When wiring automated CI test triage with claude -p, enforce strict job isolation:
- Run the PR’s tests in a job with no secrets and upload the test log as an artifact.
- Run the read-only Claude triage step in a separate job on a fresh runner that downloads the artifact, uses bare/restricted isolation flags so PR hooks, settings, and
.mcp.jsoncannot execute, caps spend, and never runs Bash or PR code while API credentials are present. - Protect
.github/underCODEOWNERSso pull requests cannot weaken the workflow.
Consult the official Claude Code documentation for exact headless isolation flags and GitHub Action syntax.
When Claude Code tests lie or flake
Section titled “When Claude Code tests lie or flake”- Claude weakened an assertion to turn the suite green. Revert the test file via git, restart implementation with test edits denied, and add a CI oracle-protection check that flags combined code-and-test edits (protecting the oracle).
- The suite is green while production fails. You tested mocks instead of seams. Re-run with real middleware/handlers and add scheduled contract tests against external sandboxes.
- A
PostToolUsetest hook runs yet Claude ignores failures. Confirm the script prints errors to stderr and exits2rather than1. - The
Stophook stalls every turn. ScopeStopto fast unit tests andPostToolUseto related tests; keep slow integration and E2E suites in CI. - E2E tests pass locally and flake in CI. Remove every fixed sleep (
waitForTimeout), switch to web-first assertions and URL checks, and require three consecutive passes. - Tests shatter on safe refactors. Rewrite assertions around observable inputs, HTTP statuses, and persisted state rather than private helpers or internal call order.
- Tests pass individually and fail together. Eliminate shared mutable fixtures, reset mocks in
beforeEach, and wrap DB tests in rolled-back transactions.
Official docs and next steps
Section titled “Official docs and next steps”Refer to the official Claude Code documentation for current permission flags, hook schemas, and headless CI options.
Working across agents? Compare testing with Codex and TDD in Cursor.
Did this guide help you?
One tap, no sign-in.
What will you do with it?
How did it read?
What got in the way? Pick any that apply
Your role?
Thanks. I read every answer. Michał Jaskólski
Did this guide help?
One tap each. Close whenever you like.
no sign-in