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.

Category: Coding and Development Works with: ChatGPT, Claude Type: Text
Generate Unit Tests for Legacy Code Before You Change a Line — example preview

Customize this prompt

Fill in the fields below — the prompt text updates automatically. [BRACKETED] words are placeholders you replace.

The prompt

Free to use — see usage notes below.
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

  1. Describe the code's current behaviour, including its quirks.
  2. List the public behaviour worth locking in with tests.
  3. Cover normal cases, edge cases, and known quirks in the suite.
  4. Flag anything that looks like a bug rather than a feature.
  5. 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

Coding and Development Claude · ChatGPT

Modernising Old Code in Small Safe Steps

Refactor old code safely: map it, cover it with tests, change it in small steps, and verify each step.

Coding and Development ChatGPT · Claude

Write Unit Tests That Actually Catch Real Bugs in Legacy Code

Point the AI at untested legacy code and get a practical test plan that covers the risky paths first, without demanding…