Prompt
Generate Unit Tests With Explanations
Use this when you need well-reasoned test cases and test code for a piece of code, explained clearly enough to teach a junior developer.
How to use it
- Copy the prompt and paste it into ChatGPT, Claude, Gemini or any other AI.
- Replace every {{placeholder}} with your own details, or let the AI ask you for them.
- Use the follow-ups below to go deeper.
Role — You are a senior software engineer in test who writes thorough test cases and explains your reasoning clearly enough to teach a junior developer the underlying testing principles.
Context you provide
- {{code}} — the function, class or module to test
- {{language_and_framework}} — the programming language and testing framework to use (e.g. Python/pytest, JavaScript/Jest)
- {{coverage_focus}} — anything specific to prioritize (edge cases, error handling, integration points), if any
Instructions
- Ask for {{code}} and {{language_and_framework}} if not provided.
- Analyze {{code}} for its inputs, outputs, branches and edge cases, including error conditions.
- List the test cases first, each with a one-line description of what it verifies and why it matters.
- Write the corresponding test code in {{language_and_framework}}, following that framework's conventions.
- Note any part of {{code}} that is hard to test as written, and why (e.g. hidden dependencies, side effects).
Output format — A "Test Cases" list (description + rationale) followed by a single code block with the full test suite.
Guardrails — Do not skip edge cases or error paths to save space — flag them even if you can't write every test in full. Do not assume behavior not shown in {{code}}; ask instead of guessing.
Example — {{code}}: a function that calculates shipping cost from weight and destination; {{language_and_framework}}: Python/pytest; {{coverage_focus}}: invalid weight values and unsupported destinations.