# Test generation and TDD with Claude Code

URL: https://developertoolkit.ai/en/claude-code/test/testing/
Description: Use Claude Code for pattern-matched tests, locked-test red-green-refactor loops, hook-driven feedback, seam-level integration tests, and mutation checks.

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

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](/en/workflows/plan/acceptance-criteria/) for how test cases enter this loop and [the evidence bundle](/en/workflows/ship/evidence-bundle/) for what every PR carries.

## 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](/en/claude-code/automate/hooks-automation/) for full hook wiring, JSON output contracts, and fixture tests, and check the [official Claude Code documentation](https://code.claude.com/docs/en/hooks) for current event schemas.

## 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](/en/workflows/test/protect-the-oracle/) and [test-driven development with AI](/en/method/principles/test-driven-development/).

**Copy-paste prompt: pattern-matched seam integration test**

```text
Read two existing test files first and list the conventions used (nesting, fixtures, mocks, assertions):
- src/services/user.service.test.ts
- src/services/project.service.test.ts

Then propose test names (one line each) for an integration test of POST /orders running the real HTTP middleware and handler, mocking ONLY the external payment provider and DB driver errors.
Must cover: happy path (201 + persisted row), validation error (400), payment provider failure (402), DB write failure AFTER successful charge (retryable 503), and idempotency (repeated key charges once).
Wait for my approval of the list. After approval, write ONLY the failing test file, run it, and show the failure output. Do not edit the route.
```

## 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](/en/ecosystem/mcp/)).
- **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](https://modelcontextprotocol.io)) 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

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:

**Copy-paste prompt: planted-bug mutation check**

```text
On src/routes/orders.ts, introduce five plausible bugs one at a time (wrong status code, skipped idempotency check, swallowed DB error, skipped validation, charging before validating).
After each single edit, run the route test suite, record whether it turned red and which test caught it, then revert only that edit.
Return a table: bug | caught (yes/no) | catching test. For every survivor, propose the missing assertion. Do not edit any test file.
```

See [oracle strength](/en/workflows/test/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](/en/harness-audit/)).

## 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](/en/claude-code/automate/custom-commands/), [Agent Skills](https://agentskills.io), and [skills.wondel.ai](https://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](https://code.claude.com/docs) for exact headless isolation flags and GitHub Action syntax.

## 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](/en/workflows/test/protect-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.

## Official docs and next steps

Refer to the [official Claude Code documentation](https://code.claude.com/docs) for current permission flags, hook schemas, and headless CI options.

- [How strong is your oracle?](/en/workflows/test/oracle-strength/) — Set mutation-score and flake-rate bars for autonomous loops.
- [Protecting the oracle](/en/workflows/test/protect-the-oracle/) — Lock acceptance tests and CI gates outside agent write access.
- [Hooks automation](/en/claude-code/automate/hooks-automation/) — Wire PostToolUse, Stop, and PreToolUse guardrails with fixture tests.
- [Automated code reviews](/en/claude-code/ship/review-automation/) — Layer independent /code-review and CI gates after tests pass.

Working across agents? Compare [testing with Codex](/en/codex/test/testing/) and [TDD in Cursor](/en/cursor-ide/test/testing-tdd/).
