Course contentsShow
← Software Engineering
Lesson 515 of 1,93315. Test-Driven DevelopmentFree lesson

Legacy Code Without Tests

Strategies for introducing TDD when working with untested legacy systems that lack seams for testing.

Legacy Code Without Tests

You'll learn strategies for safely introducing TDD practices into untested legacy codebases that weren't designed with testing in mind.

The Legacy Code Challenge

Legacy code often arrives as a tangled web of dependencies with no seams—places where you can insert tests. Classes instantiate their own dependencies directly, making it impossible to substitute test doubles. Methods are long and complex, tightly coupled to databases, file systems, or external services. You can't write tests without changing the code, but changing untested code is risky.

Starting Strategies

Characterization Tests: Before changing anything, write tests that describe what the code currently does, even if it's buggy. These act as a safety net detecting unintended changes. You're not testing correctness—you're capturing existing behavior.

The Sprout Method: When adding new functionality, write it as a separate, testable method first with its own tests. Call this new method from the legacy code. Your new code follows TDD principles, while minimizing changes to the dangerous legacy code.

The Wrap Method: Similar to sprouting, but instead of inserting your new code into an existing method, you rename the old method and create a new one that calls both the old and new logic. The new logic is tested; the old remains untouched initially.

Finding Seams: Look for constructor parameters, method arguments, or protected methods you can override in a test subclass. Even a small seam lets you break one dependency and write your first test.

Incremental Safety: Start with the parts you need to change. Don't try to test everything at once. Each test makes the next one easier.

Key Takeaway: Legacy code without tests requires tactical, incremental approaches—use characterization tests for safety, sprout or wrap new code with tests, and gradually introduce seams rather than attempting wholesale test coverage.