# How do you write tests first so a coding agent can check its own work?

Date: 2026-04-14 · Author: Robert Scales · https://guidetoartificialintelligence.com/en/learn/write-tests-first-so-coding-agent-check/

**Answer:** Write small automated tests that describe the behavior you want, run them to confirm they fail, commit them, and only then ask the coding agent to write code until every test passes without touching the test files. The tests become a target the agent can run after each change, so it checks its own work instead of asking you whether it is done.

A **coding agent** is an AI tool, such as Claude Code or OpenAI's Codex, that reads your project, edits files and runs commands to complete a programming task. Its weak spot is knowing when it has succeeded. Asked to "fix the price parser," it may write plausible code and declare victory. Give it a set of tests instead, and "done" becomes something it can measure: run the tests, read the failures, change the code, run them again.

This is an old method applied to a new kind of programmer. **Test-driven development** (TDD), associated with the software engineer Kent Beck, works in a short loop often called red, green, refactor: write a test that fails (red), write just enough code to pass it (green), then tidy the code while keeping the tests passing. Anthropic's guide to agentic coding with Claude Code recommends exactly this pattern for agents, adding one rule: the agent must make the tests pass without changing them.

## Step 1: Describe the behavior as tests

Suppose a small shop app needs a function that turns price text typed by staff into a whole number of cents. Before any code exists, write down what "correct" means. This example uses Python and **pytest**, a widely used testing tool that finds functions whose names start with `test_` and runs them.

```python
# tests/test_prices.py
import pytest
from prices import parse_price

def test_plain_dollars():
    assert parse_price("$12") == 1200

def test_cents_and_thousands():
    assert parse_price("$1,234.50") == 123450

def test_spaces_and_no_symbol():
    assert parse_price("  7.05 ") == 705

def test_rejects_words():
    with pytest.raises(ValueError):
        parse_price("twelve dollars")

def test_rejects_three_decimals():
    with pytest.raises(ValueError):
        parse_price("$1.005")
```

Each test is one sentence of the specification. The last two matter as much as the first three: they say what the function must refuse. Edge cases are where agents, like people, tend to cut corners.

Add a placeholder so the import works:

```python
# prices.py
def parse_price(text):
    raise NotImplementedError
```

## Step 2: Watch them fail, then commit

Run the tests:

```bash
pytest -q
```

All five should fail. That step is not a formality. A test that passes before any code is written is broken, since it would also pass if the code were wrong. Seeing red proves each test can catch a mistake.

Now save the tests in version control, so you have a fixed reference point:

```bash
git add tests/test_prices.py prices.py
git commit -m "Add failing tests for parse_price"
chmod a-w tests/test_prices.py     # make the test file read-only
```

## Step 3: Hand the agent the target

```prompt
The tests in tests/test_prices.py describe the behavior of parse_price in prices.py.
They currently fail. Implement parse_price so that all of them pass.

Rules:
- Do not modify, delete, rename or skip any test, and do not edit files in tests/.
- Run `pytest -q` after each change and keep going until every test passes.
- If you believe a test is wrong, stop and explain why instead of changing it.
- When finished, show me the final code and the last test output.
```

The agent now has a loop it can run alone: edit, test, read the error, edit again. Anthropic's guide notes that agents perform best when they have a clear target to iterate against, and a test suite is the clearest one available. Claude Code also asks permission by default before changing files or running commands, so you can watch each step at first.

## Step 4: Check the agent's claim

When the agent says it is finished, verify two things yourself:

```bash
pytest -q                                  # every test passes
git diff --exit-code HEAD -- tests/        # tests unchanged since your commit
```

The second command prints nothing and exits successfully if the test folder is identical to what you committed. Then read the code. Passing tests prove the listed cases work; they don't prove the code is clear, or that it handles a case you forgot to write down.

> **Try it:** Pick a small function you need, such as one that checks whether a postal code is valid. Write five tests, including two that must be rejected, and confirm all five fail. Commit them, give your coding agent the prompt above, and run both checks when it reports success.

## How do you stop it from changing the tests?

Tell it, then make sure it cannot quietly ignore you. An instruction in the prompt is the first layer. Repeat it in the project file the agent reads at the start of every session, such as `CLAUDE.md` for Claude Code, so the rule survives a new conversation.

The second layer is your setup. Commit the tests before the agent starts; then any edit shows up in `git diff`. Making the test files read-only, as above, turns a casual edit into a visible permission error. Keep the agent's permission prompts on for file edits, and say no to any change in `tests/`. Anthropic warns that skipping permission checks is risky and should happen only in an isolated container.

The third layer is an automatic check. In your continuous-integration system, the service that runs checks on every change, add a step that fails if any test file differs from the reviewed version. A few extra tests the agent never sees, kept outside its working folder and run only by you, also help: code written to fit the visible tests too narrowly will often fail them.

Finally, keep a door open. Sometimes a test really is wrong. Asking the agent to stop and explain, rather than edit, means you decide, and the tests remain the description of what you want.

## Sources

- Claude Code: Best practices for agentic coding: https://www.anthropic.com/engineering/claude-code-best-practices
- Test-driven development (Wikipedia, revision of 23 March 2026): https://en.wikipedia.org/w/index.php?title=Test-driven_development&oldid=1344926507
