AI Coding

How to Write Unit Tests With AI (Without Fake Coverage)

Ask an AI assistant to write unit tests and you’ll get a neat file in seconds. Every test passes. The coverage report turns green. And the bug you were worried about can still be sitting right there. This guide shows how to write unit tests with AI so the tests actually check behaviour, using a small Python experiment we ran with pytest and coverage.py on 16 November 2026.

We didn’t benchmark any AI product here. We built three test suites for one buggy function on purpose, each in a style you’ll recognise from AI output, and measured what they catch. The numbers are small. They’re also real, and the scripts are in our data folder so you can rerun them.

Quick answer: To write unit tests with AI, give the assistant the spec (expected inputs and outputs, edge cases), not just the code. Ask for tests that would fail on a wrong answer, run them, then check them with branch coverage plus a few deliberate bugs (mutants). Coverage alone proves lines ran, not that results were checked.

  • In our run, all three suites hit 100% line and branch coverage on a buggy function. Only one of them failed.
  • Tests whose expected values copy the code’s formula pass on the bug and break when you fix it.
  • The spec-based suite killed 7 of 7 killable mutants; the “looks fine” suite killed 2.
  • GitHub Copilot’s own docs say its generated tests “may not cover all scenarios” and need review.

Why AI unit tests go wrong

An assistant that only sees your function has one source of truth: the function. So it writes tests that describe what the code does today. If the code is right, great. If the code has a bug, the tests describe the bug and call it correct.

Two failure patterns show up again and again in generated tests. The first is the weak assertion: assert result is not None, isinstance(result, float), or “express costs more than standard”. These run the code and check almost nothing. The second is the mirror test, where the expected value is computed with the same formula as the code under test. It feels thorough because it uses real numbers. It isn’t.

Both patterns push coverage to 100%. That’s the trap.

Our test: one bug, three suites

The function is a tiny shipping calculator. The spec says: parcels up to and including 1 kg cost $5.00; above that, add $2.00 for every started extra kilogram (so 1.2 kg costs $7.00); express doubles the fee; zero or negative weight raises an error. Our version has one realistic bug. It uses int(weight_kg - 1) where it should use math.ceil, so a 1.2 kg parcel is charged $5.00 instead of $7.00.

def shipping_fee(weight_kg: float, express: bool = False) -> float:
    if weight_kg <= 0:
        raise ValueError("weight must be positive")
    if weight_kg <= 1:
        fee = 5.0
    else:
        extra = int(weight_kg - 1)  # BUG: should be math.ceil(weight_kg - 1)
        fee = 5.0 + 2.0 * extra
    if express:
        fee = fee * 2
    return fee

Then we wrote three suites against it:

  • Weak: four tests that check the return type, that heavy parcels return something, that express costs more, and that zero raises ValueError.
  • Mirror: a parametrized test where the expected fee is calculated with int(w - 1), the same formula as the code, plus an express check and a negative-weight check.
  • Spec: expected values typed in from the written rules, including the boundaries at exactly 1 kg, exactly 2 kg and 2.01 kg.

We ran each one under coverage.py with branch measurement (coverage run --branch -m pytest) on Python 3.12.4, pytest 9.2.0 and coverage.py 7.17.3, Windows 10. First against the buggy code, then against the fixed version.

Writing unit tests with AI: three pytest suites all at 100% coverage, only the spec suite caught the bug
Weak suiteMirror suiteSpec suite
Line coverage100%100%100%
Branch coverage100%100%100%
On the buggy code4 passed7 passed3 failed, 5 passed
On the fixed code4 passed3 failed, 4 passed8 passed
Mutants killed (fixed code)2 of 7not meaningful7 of 7

Read the middle column twice. The mirror suite passed on broken code and failed on correct code. If an assistant (or a tired human) sees those three failures after the fix, the “obvious” move is to change the code back so the tests go green again. The test suite would be actively protecting the bug.

How to write unit tests with AI, step by step

Here’s the workflow that follows from those results. It works the same in ChatGPT, Claude Code, GitHub Copilot or Cursor, because the problem is the input you give the model, not the brand.

Steps to write unit tests with AI: spec first, behaviour prompt, run, review, mutate

1. Write the spec down first

Before you open the chat, write five to ten lines describing what the function should do. Inputs, outputs, edge cases, error cases. A docstring is fine. This is the part people skip, and it’s the part that decides whether the tests are worth anything. If you can’t write the rules, the AI can’t test them either; it can only describe the code.

2. Prompt for behaviour, not for “tests”

“Write tests for this file” invites the weak style. Ask for specific behaviour checks and forbid the two bad patterns by name:

Write pytest unit tests for shipping_fee() using ONLY the spec below.
Spec: [paste rules]
Rules for the tests:
- Hard-code every expected value from the spec. Never recompute it with
  the same formula the function uses.
- Every test must assert an exact value or an exact exception.
- Cover each boundary: exactly at the limit, just below, just above.
- Use @pytest.mark.parametrize for the input/expected table.
- After the tests, list any spec rule you could NOT test and why.

Anthropic’s Claude Code workflow docs give similar advice: be specific about the behaviour you want verified and ask for edge cases such as boundary values and error conditions. GitHub’s guide to writing tests with Copilot offers the /tests slash command for a whole file, and it warns that the generated tests “may not cover all scenarios”, so you still review and add cases.

3. Run the tests against the code you have

Run them before you trust them. A red test from a spec-based suite is good news: it found a gap between the rules and the code. In our run, the spec suite failed three cases on the buggy version (1.2 kg, 2.01 kg and the express check) and every one of them pointed straight at the int versus ceil line.

Don’t let the assistant “fix” a failing test by editing the expected value unless you’ve confirmed the spec was wrong. That single habit removes most fake coverage.

4. Read every assertion

It takes a couple of minutes for a small file. Look for asserts that only check type or “not None”, expected values built by calling helper code, comparisons between two calls of the same function, and tests with no assert at all. If you’d struggle to say which bug a test would catch, it probably catches none.

5. Measure branches, then break the code on purpose

Turn on branch coverage so you see conditions that never went the other way. Then do a cheap mutation check: change one thing in the code (a <= to <, a constant, a ceil to round) and rerun the suite. A good suite fails. Our script applied eight hand-made mutants to the fixed function. One of them can’t be detected at all, because at exactly 1 kg both branches return $5.00 (an “equivalent mutant”). Of the seven that can be caught, the spec suite caught seven and the weak suite caught two.

AI unit testing mutation check: spec-based tests killed 7 of 7 mutants, weak tests killed 2

You don’t need a framework for this on small modules. For bigger codebases, mutation-testing tools such as mutmut automate the same idea, but they’re slow, so most teams run them on the files that matter most.

The catch: 100% coverage was the one number all three suites shared, including the two that let the bug through. Coverage tells you which lines ran during the tests. It says nothing about whether any result was checked. So “the AI got us to 100% coverage” is a statement about effort, not about safety. If your team has a coverage gate in CI, an assistant can satisfy it with tests like our weak suite in seconds.

What a good AI-written test looks like

This is the core of our spec suite. Notice that every expected number comes from the rules in plain English, and the boundary cases sit right next to each other so a reviewer can scan them.

@pytest.mark.parametrize("w, fee", [
    (0.5, 5.0),
    (1, 5.0),      # boundary: exactly 1 kg
    (1.2, 7.0),    # one started extra kg
    (2, 7.0),      # boundary: exactly 2 kg
    (2.01, 9.0),   # just over 2 kg
])
def test_fee_from_spec(w, fee):
    assert shipping_fee(w) == fee

pytest’s parametrize decorator turns that table into five separate tests, so a failure report names the exact input that broke. Ask the AI for this table shape. It’s easy to review and hard to fake.

One honest limit: we compared floats with == because every value here is a clean multiple of 0.5. For real money code, use integers in cents or pytest.approx, and say so in your prompt.

Common mistakes and quick fixes

MistakeWhat it looks likeFix
Code-only prompt“Write tests for utils.py”Paste the spec and the edge cases you care about
Mirror expected valuesexpected = 5 + 2 * int(w - 1)Hard-code values from the spec
Weak assertsis not None, isinstanceAssert exact values or exact exceptions
Over-mockingThe function under test is mocked awayMock only I/O (network, disk, clock)
Green-washingAI edits expected values until tests passOnly change a test after checking the spec
Line coverage only100% with untested conditionsAdd --branch and a few mutants

If a test fails and you’re not sure whether the code or the test is wrong, treat it like any other bug hunt. Our guide on fixing bugs with AI without making things worse walks through that loop.

Which AI tool to use for tests

Any assistant that can read your project and run commands will do better than a chat window, because it can run the suite and see the failures itself. In an editor, Copilot’s /tests command is the fastest start; our GitHub Copilot tutorial covers the setup. Terminal agents like Claude Code and Codex can run pytest, read the output and iterate, which suits the spec-first loop above. For the trade-offs between them, see our Claude Code vs Codex vs GitHub Copilot comparison.

The tool matters less than the rule you give it. An agent that’s allowed to edit both the code and the tests, with no spec, will happily make them agree with each other.

Verdict

Use AI for unit tests. It’s good at the boring part: the table of cases, the parametrize boilerplate, the fixtures. Don’t use it as the source of truth for what “correct” means. That has to come from you, written down, before the prompt.

Skip AI test generation for code that has no spec at all, unless your goal is a characterization test that freezes current behaviour before a refactor. That’s a legitimate use, as long as everyone knows the tests describe the code, bugs included.

Next: tests are one half of the safety net. The other half is reading the code itself, which we cover in how to review AI-generated code.

FAQ

Can AI write unit tests?

Yes. Copilot, Claude Code, ChatGPT and others all generate runnable pytest, Jest or JUnit tests. The quality depends on what you give them. With only the code, they tend to test what the code does; with a written spec, they can test what it should do.

Should AI write unit tests for my project?

It’s a fair use if a person reviews every assertion and the expected values come from requirements. It’s risky if the AI writes both the code and the tests in one go with no human-written rules, because the two can agree on the same mistake.

Does 100% code coverage mean the tests are good?

No. In our experiment, three suites reached 100% line and branch coverage and two of them missed a pricing bug. Coverage shows what ran. Assertions decide what was checked.

What is mutation testing, in one line?

You make small deliberate bugs in the code and see whether the tests fail. Each bug the tests catch is “killed”. Mutants that survive show you where the suite is blind.

Leave a Comment