Best Division

Spread Your Knowledge

  • All topics
  • About us
  • Contact us
  • Privacy policy
  • Terms of service
  • Copyright
  • Facebook
  • Twitter
  • Instagram
  • Youtube
  • LinkedIn
  • Pinterest
  • Github
  • Tumblr

© 2026 Best Division

How Do You Write Unit Tests for Legacy Code?

Software Testing
Jayant Kumar
Jayant Kumar@jayantkumar314
PublishedNov 29, 2026
9 min read

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.

Table of Contents

  • Why testing legacy code is different
  • Characterization tests pin down current behaviour
    • Approval (golden master) tests for large outputs
  • Finding seams to break dependencies
  • Adding new code safely with sprout and wrap
  • Growing coverage where it matters
  • Frequently Asked Questions
    • Should I refactor before writing tests?
    • What if the existing behaviour is a bug?
    • Is it worth rewriting legacy code instead?
    • How do I convince a team to invest in this?
  • Summary
  • Related Articles

Why testing legacy code is different

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:

  1. Do not trust the specification, trust the observed behaviour. The production behaviour, including its bugs, is what users depend on.
  2. Change as little as possible to get the first test in place. Large refactors without tests are exactly the risk you are trying to remove.

Characterization tests pin down current behaviour

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:

python

Start with a test that asserts a deliberately wrong value, run it, and copy the real value from the failure message:

python

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.

Approval (golden master) tests for large outputs

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:

python

Review the first golden file by eye before committing it. A golden master that captured wrong output protects the wrong behaviour.

Finding seams to break dependencies

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 typeHow it worksTypical use
Parameter seamPass the dependency in as an argument with a defaultClocks, random numbers, HTTP clients
Subclass and overrideExtract a method, override it in a test subclassMethods that call the network or database
MonkeypatchReplace a name at runtime with monkeypatchLast resort when you cannot change the signature
Wrapper functionHide a static or global call behind your own functionThird-party singletons, os.environ

Consider a method that cannot run in a test because it talks to a real mail server:

python

The smallest safe change is to extract the two awkward calls into methods:

python

Behaviour in production is unchanged, but a test can now subclass the service and replace _now and _send_mail:

python

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.

Adding new code safely with sprout and wrap

Sometimes you must add a feature to a function you cannot yet test. Do not write the new logic inline.

  • Sprout method or class: write the new behaviour as a separate, fully test-driven function and call it from the legacy code with one line.
  • Wrap method: rename the old method, create a new method with the old name that calls the old one and adds the new behaviour before or after.
python

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.

Growing coverage where it matters

You will never test everything, and you should not try. Prioritise by risk and change frequency:

  1. Test the code you are about to change before you change it.
  2. Use version control history to find files that change often and fail often.
  3. Add a regression test for every bug you fix, written before the fix.
  4. Measure with 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.

Frequently Asked Questions

Should I refactor before writing tests?

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.

What if the existing behaviour is a bug?

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.

Is it worth rewriting legacy code instead?

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.

How do I convince a team to invest in this?

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.

Summary

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.

Related Articles

  • What Is Code Coverage and What Percentage Is Good Enough?
  • How Do You Install pytest and Write Your First Test?
  • Learn Software Testing: Complete Roadmap from Beginner to Advanced
Share