Write unit tests that catch real bugs
Generate focused unit tests for a function, covering normal cases, edge cases and errors, in your test framework and project style.
- Published
- Works with
- ChatGPT, Claude and Gemini
- Level
- Intermediate
AI-generated tests often just repeat the code's current behaviour or test trivial things. Useful tests start from what the function should do and probe the edges where bugs live. This prompt asks for a test plan first, then tests in your framework, and flags behaviour that looks like a bug.
The prompt
You are a senior engineer who writes careful tests. Write unit tests for the code below.
Language and test framework:
Code to test:
What it is supposed to do:
Example of an existing test in my project (for style):
Steps:
1. Test plan: list cases grouped as normal, edge (empty, zero, max, unicode, boundaries, time zones), and error cases.
2. Write the tests. One behaviour per test, descriptive names, arrange-act-assert layout.
3. Mock only external dependencies (network, database, clock, random), not the code under test.
4. List any behaviour in the code that seems to contradict the expected behaviour — likely bugs.
5. Note anything that would be hard to test and suggest a small refactor.
Use only APIs that exist in my framework version. Don't change the code under test unless I ask.
How to use it
- Describe the intended behaviour, not just the code; otherwise tests will lock in existing bugs.
- Run the tests and read any failures carefully — they may reveal real bugs.
- Add the tests to CI so they run on every change.
Tips
- Ask for property-based tests for functions with many possible inputs.
- Paste a bug report and ask for a test that reproduces it before fixing.
Frequently asked questions
What does this prompt do?
Generate focused unit tests for a function, covering normal cases, edge cases and errors, in your test framework and project style.
Which AI tools does it work with?
It is written for ChatGPT, Claude and Gemini. It also works in other AI tools that accept text prompts, with small changes.
What do I need to fill in?
4 blanks: e.g. python + pytest, typescript + vitest, java + junit; paste function or class; expected behaviour, business rules; paste or "none". Click each blue blank on the page, type your details and press Copy prompt.
Is this prompt free to use?
Yes. You can copy and use it for personal and commercial work.