# Test generation and verification with Codex

URL: https://developertoolkit.ai/en/codex/test/testing/
Description: Close coverage gaps with Codex safely: parallel worktree lanes, a tests-only diff gate, branch-coverage deltas, mutation testing, and independent review.

Test generation with Codex closes coverage gaps safely when each module runs in an isolated Git worktree lane, source-code edits stay strictly forbidden during test writing, and every lane proves strength through objective checks: a tests-only diff gate, per-file branch-coverage deltas, mutation testing, and an independent `codex review` pass.

A coverage report reads 34%, the release bar is 80%, and 200 untested functions sit across dozens of files. Asking Codex to "add tests until coverage reaches 80%" will hit the number fast—often with mock-heavy tests that pass even when production logic breaks. Developers and tech leads need a verification loop that measures bug-catching strength without line-by-line diff reading.

## Separate test generation from test verification

Line coverage is the weakest proof of test quality because executing a function with no meaningful assertion still turns coverage green. Split the workflow so each artifact is checked by an independent oracle rather than the session that wrote the tests ([how strong is your oracle?](/en/workflows/test/oracle-strength/)):

| Artifact | Producer | Verification mechanism | Sign-off |
| --- | --- | --- | --- |
| Risk-ranked gap list | Codex (read-only) | Human reviews 10-row risk table | Developer |
| Planned behavior test names | Codex (in lane) | Human approves short behavior list before implementation | Developer |
| Generated test files | Codex (worktree lane) | Tests-only diff gate + repeated green runs (flake check) | Automated gate |
| Coverage gain | Test runner | Per-file branch-coverage delta against lane baseline | Automated gate |
| Bug-catching strength | Mutation runner (e.g., StrykerJS) | Mutation score and surviving mutants list | Reviewer inspects survivors |
| Test integrity | Independent `codex review` | Adversarial audit for tautologies and mock drift | Reviewer reads flagged tests |
| Merge decision | CI on clean runner | Full suite, types, lint, and protected oracle checks | Code owner on evidence |

## Prepare the repository oracle before launching lanes

1. **Declare exact test commands in `AGENTS.md`.** Trust the repository first so Codex loads project `AGENTS.md`, then list the exact single-file, full-suite, and JSON coverage commands plus two explicit rules: never weaken a test to make it pass, and never edit production source files during a test-writing task ([AGENTS.md optimization](/en/codex/build/agents-md-optimization/)).

2. **Install coverage and mutation tooling on the default branch first.** Commit your coverage provider and mutation runner configuration (ignoring report and temporary sandbox directories in `.gitignore`) on `main` before creating any lane. Every lane branches from that base commit and never touches `package.json` or lockfiles.

3. **Capture a clean baseline coverage report.** Run coverage yourself on the base commit so gap analysis works from real data. Optionally add a shared TDD Agent Skill ([Agent Skills standard](https://agentskills.io), [skills ecosystem](/en/ecosystem/skills/)) if you want behavior-first planning across sessions.

## Rank gaps by business risk, then run isolated lanes

Low coverage in a static configuration loader carries far less risk than missing branch coverage in billing, authorization, or persistence code. Run a read-only Codex pass against your coverage summary and source tree to rank the highest-risk uncovered branches and partition target files into 2–4 disjoint ownership lanes with zero shared fixtures. Approve that concise table before generating a single test.

For each approved lane, create an isolated branch and checkout via [isolated Git worktrees](/en/codex/automate/worktrees/), install dependencies from your own terminal (since workspace sandboxes restrict network egress), and record a fresh per-lane coverage baseline so absolute file paths match that worktree.

Follow three non-negotiable rules inside every test-generation lane:

- **Approve behavior names before code:** Reviewing 15 planned test descriptions takes one minute; reviewing 400 lines of unfamiliar test boilerplate rarely catches missing edge cases. Require coverage of exported functions, error throws, catch paths, and boundary values (zero, empty, max length, invalid state transitions).
- **Assert observable behavior, never internal mocks:** Mock only external system edges (database client, payment gateway, email transport). Assert return values, thrown errors, persisted records, and outbound calls that define the contract.
- **Apply the `BUG?:` rule instead of editing `src/`:** When a newly written test fails because production code contains a real bug, agents feel strong pressure to rewrite the assertion to match the broken output. Forbidding edits under `src/` and instructing Codex to mark the test skipped with a `BUG?:` note converts silent bug-masking into an explicit triage item for a human engineer.

For current non-interactive `codex exec` and sandbox flags when running multiple lanes in parallel, check the [official OpenAI Codex documentation](https://developers.openai.com/codex).

## Prove generated tests catch bugs before reading a single file

Run four sequential verification gates inside each worktree lane and reject the lane on the first mechanical failure:

1. **Tests-only and determinism gate.** Verify `git status` shows changes strictly under `tests/` (zero edits to `src/`, config, or lockfiles). Run the generated test files multiple times in a row (for example, five consecutive runs) to reject flaky tests before they ever reach CI, and compute per-file branch-coverage deltas against the lane's own baseline.

2. **Scoped mutation testing.** Run mutation testing (such as StrykerJS for TypeScript/JavaScript or your language's equivalent) scoped strictly to the lane's target source files. Line coverage proves execution; mutation testing flips conditionals, boundary operators (`>` to `>=`), and return values to prove assertions actually notice broken behavior. Feed surviving mutants back to the lane as required missing assertions.

3. **Adversarial review pass.** Run `codex review` in a fresh process—or a dedicated read-only audit prompt—asking four hostile questions for every test: Would this pass if the function returned a hardcoded constant or skipped persistence? Does it assert only truthiness or mock invocation? Do mock return shapes match the real dependency's implementation? Does it depend on ordering, wall-clock time, or shared state? ([code review with Codex](/en/codex/ship/code-review/)).

4. **Attach the evidence bundle and lock the oracle.** Open the pull request carrying branch-coverage deltas, mutation scores and surviving mutants, any `BUG?:` items, and flagged audit lines ([the evidence bundle](/en/workflows/ship/evidence-bundle/)). Protect `tests/` with `CODEOWNERS` and CI oracle checks so future agent tasks cannot silently delete or loosen assertions ([protecting the oracle](/en/workflows/test/protect-the-oracle/)).

## Prevent test decay after the coverage push

A strong test suite degrades within months if new code lands untested or flakes accumulate quietly. Hold the gain with two controls:

- **Ratchet CI thresholds upward:** Enforce branch and line thresholds in your test runner configuration, raise them as lanes merge, and refuse pull requests that lower thresholds to get green.
- **Schedule read-only test-health audits:** Run periodic non-modifying checks that execute the suite multiple times to flag emerging flakes, report per-file branch-coverage drops against a human-reviewed baseline commit, and list aging skipped tests (`it.skip` / `it.todo`). Always update coverage baselines in reviewed human commits so an automated run can never erase its own regression.

Run `npx @wondelai/harness-audit` ([Harness Audit](/en/harness-audit/)) periodically to verify test commands, oracle protections, and `AGENTS.md` rules remain intact.

## When Codex test generation goes wrong

| Symptom | Root cause | Recovery |
| --- | --- | --- |
| Line coverage rose while mutation score stayed flat | Tests execute paths but assert only mocks or truthiness | Run adversarial audit; re-prompt the lane with exact surviving mutants as required assertions |
| Gate flags modified files outside `tests/` | Codex edited `src/` to make a failing assertion pass | Discard non-test edits (`git checkout -- src/`), enforce the `BUG?:` rule, and triage the production behavior manually |
| Target source file shows zero coverage delta | Tests mocked out the module under test or imported the wrong path | Point Codex to exact uncovered line numbers and verify single-file coverage output |
| Lane passes locally but breaks after merge | Stale base branch or two lanes mutated a shared fixture | Rebase onto `main` and rerun the full gate; isolate shared fixture changes into a dedicated prerequisite PR |
| Mocks diverge from real runtime behavior | Mocks were inferred from tests rather than dependency source | Constrain mocks to real exported types and pair unit suites with thin seam integration tests ([testing hub](/en/workflows/test/)) |
| Worktree fails immediately with missing packages | Fresh worktrees exclude gitignored `node_modules` and offline sandboxes block installs | Bootstrap dependencies from your terminal before starting the lane |
| Codex ignores `AGENTS.md` test commands | Repository or worktree path is untrusted | Trust the repository path explicitly after inspecting it, then start a clean session |

## Official docs and next steps

Refer to [developers.openai.com/codex](https://developers.openai.com/codex) for current sandbox, worktree, and `codex exec` / `codex review` options.

- [Protecting the oracle](/en/workflows/test/protect-the-oracle/) — Prevent future agent sessions from weakening, skipping, or rewriting your test assertions.
- [How strong is your oracle?](/en/workflows/test/oracle-strength/) — Evaluate assertion strength, mutation scores, and when a green suite actually proves correctness.
- [Code review with Codex](/en/codex/ship/code-review/) — Pair test generation with calibrated pre-push and pull-request review gates.
- [Testing workflows hub](/en/workflows/test/) — Tool-neutral testing strategy: dependency verification, fitness functions, and slop detection.

Working in other agents too? See [test generation and TDD with Claude Code](/en/claude-code/test/testing/) and [testing patterns in Cursor](/en/cursor-ide/test/testing-tdd/).
