Testing legacy code means adding automated tests to code that was written without them, so you can change it safely. The reliable approach is to first pin down what the code does today with characterization tests, create seams that let you isolate the code from databases, clocks and networks, and only then refactor. You do not need to understand or fix everything before the first test.
Michael Feathers defined legacy code as code without tests, and that definition is useful: age and quality do not matter, only whether you can change it with confidence. This guide assumes you already know how to write fast, isolated unit tests and focuses on the tactics that make hard-to-test code testable. The examples use Python with pytest, but the techniques apply to any language.
In new code you write a test, watch it fail, then make it pass. In legacy code the behaviour already exists, it is often undocumented, and the structure fights you: classes create their own database connections, call datetime.now() directly, read environment variables and write to files. A function with 400 lines and nine side effects cannot be called from a test without a running system.
Two rules shape everything that follows:
A characterization test records what the code actually does for a given input. You do not decide what the answer should be; you run the code, observe the result, and assert it. The test then acts as an alarm: if a later change alters the behaviour, it fails.
Suppose you inherit this function:
Start with a test that asserts a deliberately wrong value, run it, and copy the real value from the failure message:
The third test records a surprising rule: the flat 5 deduction is applied after the percentage, and the result is clamped at zero. Whether that is a bug or a feature is a business question. Mark such cases with a comment and keep the test until someone decides.
When the output is big, such as a report, an HTML page or a JSON document, hand-writing assertions is slow. An approval test stores the output in a file and compares future runs with it. The approvaltests package provides this for Python, or you can write a small version yourself:
Review the first golden file by eye before committing it. A golden master that captured wrong output protects the wrong behaviour.
A seam is a place where you can change behaviour without editing the code at that place. Feathers describes several kinds; the most common in modern code are:
| Seam type | How it works | Typical use |
|---|---|---|
| Parameter seam | Pass the dependency in as an argument with a default | Clocks, random numbers, HTTP clients |
| Subclass and override | Extract a method, override it in a test subclass | Methods that call the network or database |
| Monkeypatch | Replace a name at runtime with monkeypatch | Last resort when you cannot change the signature |
| Wrapper function | Hide a static or global call behind your own function | Third-party singletons, os.environ |
Consider a method that cannot run in a test because it talks to a real mail server:
The smallest safe change is to extract the two awkward calls into methods:
Behaviour in production is unchanged, but a test can now subclass the service and replace _now and _send_mail:
The extraction is mechanical, so even without existing tests the risk is low. Use your IDE's automated "extract method" refactoring when it is available; it is safer than hand editing.
Sometimes you must add a feature to a function you cannot yet test. Do not write the new logic inline.
The sprouted function gets proper unit tests today. The legacy function gains a single call, and you can cover that call later with a characterization test.
You will never test everything, and you should not try. Prioritise by risk and change frequency:
pytest --cov to find untested branches, but treat the number as a guide, not a target.Higher-level tests are acceptable as a first safety net. A few end-to-end or API-level tests that exercise the main paths let you refactor internals, then you replace them gradually with faster unit tests, following the test pyramid.
Only the minimum needed to create a seam, and prefer automated refactorings that are known to preserve behaviour. Write characterization tests first whenever you can call the code at all.
Record it in a characterization test with a clear name and comment, then fix it in a separate commit that changes the test. This keeps the fix visible in review and avoids silent behaviour changes.
Rewrites usually take longer than estimated and lose undocumented behaviour that customers rely on. Characterization tests make an incremental rewrite possible because they tell you what must stay the same.
Start with the next bug or feature: add tests only around that change. Small, visible wins, such as a bug that can no longer return, build support more reliably than a large test-writing project.
To test legacy code, pin current behaviour with characterization or approval tests, introduce seams with the smallest possible changes, and add new logic through sprout and wrap techniques that are fully tested. Grow coverage around the code you change and the bugs you fix, and refactor only once the safety net exists.