Skip to content
AI Dev Toolkit.
Esc
  • Loading…

Prompt template · Code

Prompt to write unit tests

A good prompt to write unit tests gives the model the code, your test framework and one existing test to copy the style from, then asks for normal cases, boundaries, invalid input and every error path. This template also mocks only what crosses a process boundary, and keeps any test that exposes a bug instead of bending it.

Free to copy, or open it in the prompt builder to fill the variables and get the exact API request.

268 tokens unfilled · 413 with the example below · o200k_base (GPT-4o and later)

Template

The unit test prompt template (copy it)

Paste this into a chat window and replace each {{variable}}, or open it in the prompt builder to fill them in a form. Sections are marked with XML tags, which every major model reads well.

Prompt (one message, plain text)
You are a careful {{language}} engineer who writes tests that catch real regressions and survive refactoring.

<context>
The code under test:
<code>
{{code}}
</code>

An existing test in this project, to match its style and helpers:
<style_example>
{{existing_test}}
</style_example>
</context>

<constraints>
- Test behaviour through the public interface, not private helpers or the order of internal calls.
- Cover: the normal case, boundaries (empty, zero, one, maximum), invalid input and each error the code can raise or return.
- Mock only what crosses a process boundary, such as the network, the clock or the file system. Use real objects otherwise.
- Give each test a name that states the expected behaviour.
- If the code has a bug that a test exposes, keep the test, mark it clearly, and explain the bug after the code. Never weaken a test to make it pass.
</constraints>

<output_format>
One code block with the complete test file, ready to run. After it, a short list of any behaviour you couldn’t test without changing the code, and why.
</output_format>

<task>
Write unit tests for the code above using {{framework}}. Cover the behaviour a caller relies on, including edge cases and failure paths.
</task>
For an API call: system prompt and user message

With a system prompt, the role, constraints and output format stay fixed across calls (and can be cached), while the context and task go in the user message.

System prompt
You are a careful {{language}} engineer who writes tests that catch real regressions and survive refactoring.

<constraints>
- Test behaviour through the public interface, not private helpers or the order of internal calls.
- Cover: the normal case, boundaries (empty, zero, one, maximum), invalid input and each error the code can raise or return.
- Mock only what crosses a process boundary, such as the network, the clock or the file system. Use real objects otherwise.
- Give each test a name that states the expected behaviour.
- If the code has a bug that a test exposes, keep the test, mark it clearly, and explain the bug after the code. Never weaken a test to make it pass.
</constraints>

<output_format>
One code block with the complete test file, ready to run. After it, a short list of any behaviour you couldn’t test without changing the code, and why.
</output_format>
User message
<context>
The code under test:
<code>
{{code}}
</code>

An existing test in this project, to match its style and helpers:
<style_example>
{{existing_test}}
</style_example>
</context>

<task>
Write unit tests for the code above using {{framework}}. Cover the behaviour a caller relies on, including edge cases and failure paths.
</task>

Variables

What do the variables mean?

{{language}}
The language, such as Python or TypeScript.
{{code}}
The function or module to test, including the types it uses.
{{existing_test}}
One existing test file or test from the project, so the output uses the same imports, fixtures and naming. Write “none” for a new project.
{{framework}}
The test framework and any helpers, such as pytest with hypothesis, or Vitest with Testing Library.

Use

When should I use this unit test prompt?

Use it to add tests to code that has none, to fill gaps before a refactor, or to get a first draft of edge cases you might not think of. It works best on pure functions and small modules with clear inputs and outputs; for code tangled with I/O, expect a list of things it couldn’t test, which is useful information in itself.

Read every generated test before committing it. A test that passes against buggy code just locks the bug in, so check that each assertion matches the behaviour you want, not just the behaviour the code currently has.

Structure

Why is the prompt structured this way?

The existing test is in the context because style mismatches are the main reason generated tests get rewritten: wrong import paths, a different assertion library, fixtures that already exist being rebuilt by hand. One real example is usually enough to fix that.

The constraints encode what makes tests worth keeping. Testing through the public interface lets tests survive refactoring. The boundary list (empty, zero, one, maximum) is where bugs actually live. Limiting mocks to process boundaries avoids the common failure where every dependency is mocked and the test only proves the mocks were called.

The last rule matters most. Anthropic’s guide warns that models can focus on making tests pass rather than on correct behaviour, and suggests saying so explicitly; here, a test that exposes a bug is kept and reported instead of quietly bent to match the code.

Example

Example: a filled-in unit test prompt

{{language}}
Python
{{code}}
def parse_duration(text: str) -> int:
    """Parse "1h30m", "45s" or "2h" into seconds."""
    units = {"h": 3600, "m": 60, "s": 1}
    total, number = 0, ""
    for ch in text.strip():
        if ch.isdigit():
            number += ch
        elif ch in units and number:
            total += int(number) * units[ch]
            number = ""
        else:
            raise ValueError(f"bad duration: {text!r}")
    return total
{{existing_test}}
def test_slugify_lowercases_and_joins_words():
    assert slugify("Hello World") == "hello-world"
{{framework}}
pytest, with pytest.mark.parametrize for tables of cases

What to look for. A good test file includes a case for trailing digits with no unit, such as "90". The function returns 0 there instead of raising, which is a real bug that the “keep the test and explain it” rule should surface rather than hide.

The complete filled-in prompt (413 tokens)
Filled-in prompt
You are a careful Python engineer who writes tests that catch real regressions and survive refactoring.

<context>
The code under test:
<code>
def parse_duration(text: str) -> int:
    """Parse "1h30m", "45s" or "2h" into seconds."""
    units = {"h": 3600, "m": 60, "s": 1}
    total, number = 0, ""
    for ch in text.strip():
        if ch.isdigit():
            number += ch
        elif ch in units and number:
            total += int(number) * units[ch]
            number = ""
        else:
            raise ValueError(f"bad duration: {text!r}")
    return total
</code>

An existing test in this project, to match its style and helpers:
<style_example>
def test_slugify_lowercases_and_joins_words():
    assert slugify("Hello World") == "hello-world"
</style_example>
</context>

<constraints>
- Test behaviour through the public interface, not private helpers or the order of internal calls.
- Cover: the normal case, boundaries (empty, zero, one, maximum), invalid input and each error the code can raise or return.
- Mock only what crosses a process boundary, such as the network, the clock or the file system. Use real objects otherwise.
- Give each test a name that states the expected behaviour.
- If the code has a bug that a test exposes, keep the test, mark it clearly, and explain the bug after the code. Never weaken a test to make it pass.
</constraints>

<output_format>
One code block with the complete test file, ready to run. After it, a short list of any behaviour you couldn’t test without changing the code, and why.
</output_format>

<task>
Write unit tests for the code above using pytest, with pytest.mark.parametrize for tables of cases. Cover the behaviour a caller relies on, including edge cases and failure paths.
</task>

Models

Does it work the same in ChatGPT, Claude and Gemini?

Yes, the structure works in all three: tagged sections that keep your material apart from the instructions, and an explicit output format. The tips below cover where the providers’ own guides differ for this unit test prompt.

  • Claude

    In an agent loop, Anthropic suggests telling Claude not to hard-code values or special-case test inputs, and to say if a test is wrong rather than working around it. Add that line if the model will also edit the code under test.

  • OpenAI GPT

    If the first output misses the style, add the existing test as a worked example rather than more rules. OpenAI suggests reasoning models try zero-shot first and add examples only when the output misses.

  • All models

    Run the tests. The model can’t execute code in a plain chat, so a test that looks right may fail on an import or a fixture name; an agent with a terminal can run and fix them in one pass.

FAQ

Questions people ask

Can ChatGPT write unit tests?

Yes, as a first draft you review. It works best on pure functions and small modules with clear inputs and outputs. In a plain chat the model can’t run the tests, so a file that looks right may fail on an import or a fixture name; run it before you commit, or use an agent that can run and fix it.

How do I stop tests that just mirror the implementation?

Ask for behaviour through the public interface. The template forbids testing private helpers or the order of internal calls, and limits mocks to the network, clock and file system, so a test can’t pass just because every dependency was mocked. Then check each assertion matches the behaviour you want, not only what the code does today.

What should happen when a generated test finds a bug?

Keep the test and report the bug. The template tells the model to mark the failing test clearly and explain the bug after the code, never to weaken the test so it passes. In the worked example, parse_duration returns 0 for input with no unit instead of raising an error, and a good answer surfaces that.

Should CI use this template or a system prompt?

A system prompt. This template is one message you fill per task, which suits a chat. A CI job that fills coverage gaps sends the same rules with every request, so start from the unit test generator system prompt, which also lists behaviours first and never edits the code under test.

Related

Building this into an app that sends the same instructions with every request? Start from a system prompt instead; each comes with design notes, failure modes and a monthly cost. In the system prompt library: Unit test writer.

Edited the template? Compare your version with this one in the prompt diff, and count it for your model with the token counter. Browse all 29 prompt templates.

Keep exploring