Dev tools
Unit Tests With AI: How to Write and Check Them
How to write unit tests with AI using Copilot, Claude Code or Codex: a step-by-step workflow, prompts that work, red flags and how to check the tests.
To write unit tests with AI, give the assistant the code under test, your testing framework and an example of an existing test, ask it to list test cases first (including edge cases), review that list, then let it write the tests and run them. The hard part isn't generation; it's checking. AI-written tests often pass while testing the wrong thing, copy the bug into the expected value, or mock so much that nothing real is tested. Review every assertion, watch the tests fail when the code is broken, and use coverage or mutation testing to confirm they catch real bugs.
This guide gives a practical workflow for writing unit tests with AI, prompts that work, the red flags to look for, how to verify AI-written tests, how to choose a tool, and how unit testing differs for AI agents.
Why Write Unit Tests With AI?
Unit tests are one of the most useful jobs for an AI coding assistant:
- They're repetitive. Setting up fixtures, mocks and similar cases is tedious work that AI handles quickly.
- They're easy to check. You run them and see whether they pass, and you can break the code to see whether they fail.
- They raise coverage on old code. AI can add tests to legacy modules nobody wanted to touch.
- They help agents work safely. Coding agents that can run a good test suite fix their own mistakes far more reliably.
The risk is that AI makes it easy to produce lots of tests that look thorough but prove little. A smaller set of meaningful tests beats a large set of shallow ones.
How to Write Unit Tests With AI: Step by Step
1. Give the AI the right context
Include:
- the function or class to test,
- the testing framework and version (pytest, Jest, Vitest, JUnit, Go's testing package),
- an existing test file from the same project, so it copies your conventions,
- any rules: what to mock and what not to, naming style, where test files live.
In editors like VS Code, opening an existing test file in another tab gives tools such as GitHub Copilot that context automatically. Coding agents like Claude Code and Codex can read the repository themselves; point them to the right files and put testing rules in the project's instruction file.
2. Ask for test cases before code
Ask the AI to list what it plans to test, in plain language. This is the most important step, because it's where you catch missing cases and misunderstood behaviour cheaply.
3. Review and add cases
Check the list against what the code is supposed to do, not what it currently does. Add business rules the AI couldn't know.
4. Generate the tests
Ask for the tests in small batches, one function or behaviour at a time, rather than "test this whole module".
5. Run them
Run the tests immediately. Agents can do this themselves; with chat tools, run them and paste failures back.
6. Make them fail on purpose
Change the code to introduce a bug (or let a mutation testing tool do it) and confirm at least one test fails. A test that can't fail is worthless.
7. Review like a pull request
Read every assertion. Delete tests that don't add value. Commit the tests separately from code changes when you can, so reviewers see them clearly.
AI Unit Test Prompts That Work
A good AI unit test prompt is specific about the framework, the behaviour and the edge cases. A template:
Write pytest unit tests for the function `apply_discount` in pricing.py.
Context:
- Follow the style of tests/test_cart.py (fixtures, naming, no classes).
- Don't mock the pricing rules; mock only the external tax API.
First, list the test cases you plan to write, including:
- normal cases,
- boundaries (0, negative values, maximum discount),
- invalid inputs (None, wrong types),
- error handling when the tax API times out.
Wait for my approval before writing the tests.Other prompts that help:
- "Write tests that would catch this bug: [describe a past bug]."
- "Which behaviours of this function are not covered by the existing tests?"
- "Write a failing test that reproduces this issue before fixing it."
- "Rewrite these tests to test behaviour through the public interface instead of private methods."
- "Add property-based tests for this parser that check round-trip encoding and decoding."
Anthropic's guidance suggests planning cases first and then setting concrete targets such as a branch-coverage goal; GitHub's documentation stresses being specific about test requirements, because complex scenarios need more detailed prompts.
Red Flags in AI-Written Tests
Writing unit tests with AI produces predictable mistakes. Check for these:
| Red flag | Why it's a problem | What to do |
|---|---|---|
| Expected values copied from the current output | If the code has a bug, the test locks the bug in | Derive expected values from the spec or by hand |
| Everything is mocked | The test only checks that mocks were called | Mock only slow or external dependencies |
| Tests of private methods or exact internal calls | Breaks on every refactor | Test public behaviour |
| Assertions that are always true | assert result is not None proves little | Assert specific values and states |
| Only "happy path" cases | Bugs live at boundaries and in error handling | Ask explicitly for edge and error cases |
| Huge, repetitive tests | Hard to review; easy to hide gaps | Use parametrized tests and small focused cases |
| Tests that changed to match new code | The AI may "fix" a failing test instead of the bug | Investigate every failing test before editing it |
| Made-up APIs or fixtures | Tests won't run or test something imaginary | Run them; check imports and helper names |
The most dangerous pattern is the last-but-one: when a test fails, an agent may change the test so it passes. Tell agents explicitly not to modify existing tests without asking, and review test diffs separately.
How to Check AI-Written Tests
- Run the suite and make sure the new tests pass for the right reason.
- Break the code manually in a few places and confirm tests fail.
- Use mutation testing. Tools such as Stryker (JavaScript, TypeScript, C#), PIT (Java), mutmut (Python) and cargo-mutants (Rust) make small changes to your code automatically and report which ones your tests didn't catch. It's the most objective measure of test quality.
- Look at coverage, carefully. Line and branch coverage show what was executed, not what was verified. Use it to find untested code, not as proof of quality.
- Review for readability. A teammate should understand what each test checks from its name.
AI review tools can also check test quality as part of a pull request. Our guide to AI code review covers how to set that up, and our guide to AI-generated code security explains why tests alone don't catch every risk in AI-written code.
Best AI for Unit Test Cases
The best AI for unit test cases depends on how you work:
| Tool type | Examples | Best for |
|---|---|---|
| In-editor assistants | GitHub Copilot, Cursor, JetBrains AI | Generating tests for the file you're working on |
| Coding agents | Claude Code, OpenAI Codex, Copilot's coding agent | Writing tests across a repo, running them and fixing failures |
| Chat assistants | ChatGPT, Claude, Gemini | Planning test cases and explaining tricky code |
| Specialized generators | Tools focused on automatic test generation, often for Java | Raising coverage on large legacy codebases |
Agents have one big advantage: they can run the tests and see failures, so they iterate instead of guessing. Our guide on how to use Claude Code shows how to give an agent project rules such as "run the tests after every change".
Test-Driven Development With AI
AI fits well with test-driven development (TDD):
- You describe the behaviour you want.
- The AI writes failing tests for it, and you review them.
- The AI writes code until the tests pass.
- You refactor together, with the tests as a safety net.
Writing tests first gives the AI a clear, checkable target, which reduces the chance it writes code that only looks right. It also keeps the human focused on specifying behaviour, which is the part AI can't do for you.
Unit Testing AI Agents and LLM Features
Unit testing AI agents and LLM features is a different problem, because the output isn't deterministic.
- Unit test the deterministic parts normally: prompt templates, parsers for model output, tool functions, routing logic and validation.
- Mock the model in unit tests with recorded or fixed responses, so tests are fast and repeatable.
- Test structure, not exact wording: check that output is valid JSON, follows the schema, calls the right tool, or contains required fields.
- Use evaluation suites for quality: run the real model on a set of example inputs and score results with rules or an evaluator model. These are evals, not unit tests, and usually run separately from the fast test suite.
- Test tools with bad inputs, because agents will eventually call them with unexpected arguments.
FAQ
Can AI write good unit tests?
Yes, especially for well-defined functions, and coding agents that can run tests do it well. But AI-written tests need review: they can encode existing bugs, over-mock or test implementation details. Always run them, check that they fail when the code is broken, and read the assertions.
What is the best AI unit test prompt?
Give the function, the framework, an example test file and your mocking rules, and ask the AI to list test cases, including boundaries, invalid inputs and errors, before it writes any code.
Should I trust code coverage from AI-generated tests?
Not on its own. Coverage shows which code ran, not whether the tests check the right results. Mutation testing gives a much better picture of whether tests actually catch bugs.
How do you unit test AI agents?
Unit test the deterministic parts, such as tools, parsers and prompt templates, with the model mocked. Use separate evaluation suites with real model calls to measure the quality of the agent's answers and actions.
Is it okay to let an AI agent change failing tests?
Only with review. Agents sometimes edit a failing test to make it pass instead of fixing the bug. Tell the agent not to modify existing tests without asking, and review test changes separately from code changes.