Generate Unit Tests for Legacy Code Before You Change a Line
Write a safety net of unit tests for legacy code first, so refactors and fixes can be verified instead of guessed.
Customize this prompt
Fill in the fields below — the prompt text updates automatically. [BRACKETED] words are placeholders you replace.
The prompt
Act as a senior software engineer and help me write unit tests for legacy code before I change it. The code under test is [CODE_SNIPPET] in [LANGUAGE], and its current behaviour is described here: [CURRENT_BEHAVIOUR]. First, identify the public behaviour worth locking in, including normal cases, edge cases, and known quirks I must not break. Then generate a test suite using [TEST_FRAMEWORK] that covers each behaviour with a clear test name, the input used, and the expected output. Flag any behaviour that looks like a bug rather than a feature, and list the tests I should run again after every change. Do not change the original code; only add tests.
How to use it
- Describe the code's current behaviour, including its quirks.
- List the public behaviour worth locking in with tests.
- Cover normal cases, edge cases, and known quirks in the suite.
- Flag anything that looks like a bug rather than a feature.
- Run the suite before changing code, and again after every change.
Customization tips
Swap the language and test framework for your stack, and focus the suite on the module you are about to change.
Example use case
Developers maintaining older codebases who need a safety net before refactoring.
Frequently asked questions
What if the legacy code has no tests at all?
Start with the highest-risk paths only; a small suite over critical behaviour beats a large suite nobody finishes.
Should I fix bugs the tests reveal?
Record them and fix them separately; mixing a fix into test-writing makes it unclear what the tests were meant to prove.
Share
Tags: unit testing legacy code software engineering test-driven development refactoring
Reviewed by the PromptVault editorial team on October 28, 2026.
Source notes: Daily pipeline 20261027 batch 11