Legacy code resists testing because it was typically written without testability in mind, resulting in tight coupling, hidden dependencies, and large, monolithic functions that are difficult to isolate. Additionally, legacy systems often lack clear interfaces, rely on global state, and have evolved through years of patches, making automated tests costly to write and even riskier to run without causing unintended side effects.
What Makes Code “Legacy”?
In software engineering, “legacy code” usually means code that is old, inherited from previous developers, or simply code that is hard to change safely. The term often carries a negative connotation, but not all old code is legacy. A more useful definition, popularized by Michael Feathers, is that legacy code is code without tests — because without tests, you cannot easily verify that your changes don’t break existing behavior. That lack of tests is both a symptom and a cause of the resistance to testing.
Core Reasons Why Testing Is Hard
Several structural characteristics of legacy code make testing difficult:
- Tight coupling: Functions and classes often directly instantiate their dependencies (e.g., using
newinside a method), making it impossible to substitute mocks or stubs. - Hidden dependencies: Code may depend on global variables, static methods, environment variables, or external resources like databases and file systems, which are hard to control in a test.
- Monolithic methods: A single function may do several things — parse input, call a database, write logs, and render output — making it hard to test just one behavior.
- Side effects: Many legacy functions modify global state or perform I/O, so running them in a test can have unintended consequences (e.g., sending emails, writing files).
- No clear interfaces: Without abstract interfaces, you cannot easily swap out a real component for a test double.
The Role of Dependencies and Global State
A major obstacle is the presence of static or global state. For example, a legacy module might use a singleton database connection that is initialized at startup. To test a function that uses that connection, you would need to initialize the entire application context, which may require network access, configuration files, and other services. Even if you manage to set that up, the test becomes slow and brittle, and running it may interfere with other tests if they share the same global state.
Dependency injection is a common solution, but retrofitting it into existing code can be a large refactoring effort. Without it, tests often have to rely on real dependencies, which defeats the purpose of unit testing.
Why Refactoring Before Testing Is Risky
You might think the solution is to refactor the code to make it testable, but that creates a chicken-and-egg problem: refactoring without tests is dangerous because you can’t verify you didn’t break anything. This is why the recommended approach is often to write characterization tests first — tests that capture the current behavior, even if that behavior is buggy. But writing those tests is exactly what the code resists. So you may need to do small, behavior-preserving refactorings (like extracting a method) just to get a seam for testing, and then write the test. This incremental approach is slow but safe.
Common Testing Strategies That Actually Work
Despite the difficulties, several practical strategies can help:
- Start with a characterization test: Write a test that calls a function with known inputs and asserts its current output, even if that output is not what you want. This gives you a safety net.
- Use seam-based testing: Look for places where you can intercept behavior, such as a method that can be overridden or a parameter that can be passed in. Sometimes you can introduce a seam without changing the code’s external behavior.
- Test at a higher level: If unit testing is impossible, write integration tests that exercise a whole subsystem with real dependencies, but use a test database or temporary files to avoid side effects.
- Prioritize the riskiest parts: Focus testing on the code that is most critical or most frequently changed, rather than trying to cover everything at once.
- Use dependency injection in new code: When you add new features, write them in a testable way, so you don’t add to the legacy problem.
Costs and Risks of Not Testing Legacy Code
Leaving legacy code untested has real consequences. Every change becomes a gamble: a developer might fix a bug but introduce a new one elsewhere, and without tests, that regression may go unnoticed until production. The cost of manual testing rises over time as the system grows, and the fear of breaking things slows down development. In extreme cases, teams become afraid to touch certain modules at all, leading to a “frozen” codebase that cannot evolve.
Alternatives to Full Automated Testing
If full automated testing is not feasible, some teams use manual regression checklists, but these are error-prone and time-consuming. Another alternative is to use property-based testing (e.g., with tools like QuickCheck) to generate many random inputs and check that certain invariants hold. However, this still requires the code to be callable in a controlled way. Some teams also adopt a “strangler fig” pattern, gradually replacing legacy modules with new, well-tested code, rather than trying to test the old code directly.
Frequently Asked Questions
Is legacy code always bad?
No. Legacy code may be stable and battle-tested in production. The problem is not age, but the lack of tests and the difficulty of making changes safely.
Can I test legacy code without refactoring it?
Sometimes. You can write characterization tests that call the code as-is, but if the code has hidden dependencies or side effects, you may need to at least introduce a seam, which is a small refactoring.
What is the first step to make legacy code testable?
Start by identifying the most critical and isolated parts of the code. Then try to write a simple test that calls a function with fixed inputs and asserts the output. If that fails, look for a seam — a point where you can intercept behavior, such as a method that can be overridden or a parameter that can be passed in.
How long does it take to make legacy code testable?
It depends on the code size and complexity. For a small module, it might take a few hours; for a large, tangled system, it could take weeks or months. The key is to do it incrementally, testing as you go.
Is it worth writing tests for legacy code that will be replaced soon?
If the code is scheduled for replacement, you might skip writing tests and instead focus on writing tests for the new code. However, if you need to maintain the legacy code in the meantime, a few characterization tests can still protect you from regressions.