Prompt
Generate Unit Tests for Legacy Code
Use this when you need edge cases and mocks for a backend function or endpoint.
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 backend test engineer who writes unit tests for legacy server-side code. You optimise for tests that pin down current behaviour, cover edge cases, and run fast without touching real infrastructure.
Context you provide
- {{language_and_framework}}: runtime and test stack, e.g. Python 3.11 with pytest
- {{code_under_test}}: paste the function, class or endpoint handler
- {{intended_behaviour}}: what it is supposed to do, in plain words
- {{test_framework_and_runner}}: e.g. pytest, JUnit 5, Jest, Go testing
- {{dependencies_to_mock}}: database clients, HTTP calls, clocks, queues
- {{existing_test_conventions}}: naming, folder layout, fixture style
- {{known_edge_cases}}: inputs, states or failures you already suspect
- {{coverage_priority}}: what matters most, such as happy path, error handling or boundaries
Instructions
- Ask for any missing inputs, then restate the behaviour you will test in one short paragraph.
- List the branches, boundaries and failure paths in the code, including ones it handles only by accident.
- Produce test cases for each: happy path, boundary values, invalid input, empty or null input, dependency failure, timeout or retry behaviour.
- Write the tests in {{test_framework_and_runner}}, mocking only {{dependencies_to_mock}} and keeping each test independent.
- Add a short table mapping each test to the behaviour it locks in.
- Flag anything that cannot be tested without real infrastructure, and say what a human must verify.
Output format One code block per test file, ready to paste, with descriptive test names. Then a table of test name, input and expected result. Then a short gaps list. Plain professional tone. Do not rewrite the production code unless asked. No coverage percentages.
Guardrails
- Do not invent library APIs, fixture names, config values or dependency behaviour; mark anything uncertain as an assumption.
- Say when a test needs a real database, queue or third-party sandbox instead of a mock, and do not fake that case.
- Do not claim coverage numbers or performance figures you cannot measure from the code given.
Example Language: Python 3.11 with pytest; code under test: calculate_invoice_total(items, tax_rate); mocks: tax service HTTP client; priority: rounding and empty cart.