Claude · Coding

Testing

Get failing tests that catch the bug, tests of behavior rather than implementation, table-driven cases, and a ranked list of missed edge cases.

Claude for testing

What Claude copies when it writes tests

In Claude Code, test writing starts from your repo. Anthropic's docs say Claude examines your existing test files to match their style, framework and assertion patterns, and it can run the tests it writes. So a good suite tends to produce more of the same, and a suite full of mocks gives it a poor model to copy. In a chat window it has none of that, so paste a sample test along with the code. Either way, the expected results should come from you or a spec. If Claude works out the right answer by reading the code under test, a passing test only shows the code agrees with itself.

Choose by what you have in hand

Start from what you already know. With a bug report, ask for a failing test before the fix. With a list of inputs and outputs, ask for a table-driven test. With a function you're about to depend on, write its behaviors as sentences and test those. With tests that pass while bugs still get through, ask for a ranked list of what's missing before you ask for more code. Whichever you pick, ask to see the command and its output. Anthropic's docs say a bare claim that all tests pass tells you very little.

Frequently asked
Can Claude write unit tests?

Yes. In Claude Code it reads your existing tests, matches their framework and style, writes new ones and can run them. In a chat window, paste the code and a sample test, then run the result yourself.

Why do Claude's tests pass when the code is wrong?

Usually because the expected values were worked out from the code itself, so the test records what the code does, not what it should do. Give Claude the behaviors or the expected values yourself, and ask to see a test fail before the fix.

How do I stop Claude changing tests to make them pass?

Say in the prompt not to edit, skip or delete a test, and to tell you if it thinks a test is wrong. Then check the diff. For a long unattended run, put a condition such as no test file is modified in a /goal.

Can Claude Code run my tests by itself?

Yes. Give it the test command in your prompt or CLAUDE.md and it can run the tests, read failures and fix them. Anthropic's docs recommend adding the command for running one test file to CLAUDE.md.

How do I improve test coverage with Claude?

Ask it to find functions with no tests, then to list edge cases your tests miss, such as error conditions, boundary values and unexpected inputs. Choose which cases matter before asking for the tests, because not every listed case can really happen.