Skip to content

Test 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:

ArtifactProducerVerificationSign-off
Behaviour listDeveloper or Claude from specReview 10–20 test names before any code is writtenDeveloper
Failing test (Red)Claude (test-only scope)Runs red for the expected assertion reasonSession output / hook
Implementation (Green)Claude (test files locked)Suite passes while git diff leaves test files untouchedCI
Oracle strengthIndependent check or mutation runnerPlanted defects must break the suiteReviewer reads survivor table
Merge readinessCI outside agent controlTypecheck, lint, full suite, changed-file coverageCode 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:

  1. 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.
  2. Attach a PostToolUse hook on Edit|Write to run tests related to the modified file. Exit code 2 sends stderr directly back to Claude so it fixes regressions on the next step; exit code 1 is ignored by Claude Code.
  3. Attach a fast Stop hook that blocks completion when tests fail. Check stop_hook_active so 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:

  1. 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.

  2. Write the failing test in a test-only session. Restrict writes to test files (for example via --allowedTools scoped to Edit(src/**/*.test.ts) in non-interactive mode) so the red step cannot modify production code.

  3. 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.

  4. Implement with test files denied. Run the implementation session with test edits blocked (via --disallowedTools "Edit(**/*.test.ts)" or a PreToolUse path-protection hook) and instruct Claude to stop and explain if it believes a test is wrong.

  5. Verify the test diff stayed clean, then refactor under green hooks. Confirm git diff --stat excludes test files (shell scripts can still bypass file-tool rules unless backed by OS sandboxing and CI checks), then refactor safely while PostToolUse re-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 fixed waitForTimeout calls, 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:

  1. Red-first proof. Confirm every new test failed before implementation.
  2. Repeat-run stability. Run new tests three times consecutively to catch race conditions and shared state immediately.
  3. 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.
  4. 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.json cannot execute, caps spend, and never runs Bash or PR code while API credentials are present.
  • Protect .github/ under CODEOWNERS so pull requests cannot weaken the workflow.

Consult the official Claude Code documentation for exact headless isolation flags and GitHub Action syntax.

  • 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 PostToolUse test hook runs yet Claude ignores failures. Confirm the script prints errors to stderr and exits 2 rather than 1.
  • The Stop hook stalls every turn. Scope Stop to fast unit tests and PostToolUse to 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.

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.

not at all a lot