Course contentsShow
← Software Engineering
Lesson 1754 of 1,93351. Legacy Code and Brownfield DevelopmentFree lesson

Breaking Dependencies to Enable Testing

Strategies for isolating code under test by breaking problematic dependencies on databases, files, or external systems.

Breaking Dependencies to Enable Testing

You'll learn how to strategically isolate code under test by removing or replacing problematic dependencies on databases, files, and external systems.

The Core Problem

Legacy code often has tangled dependencies that make testing nearly impossible. Imagine trying to test a function that saves user data, sends an email, writes to a database, and logs to a file—all in one go. Running a test would require a live database, an email server, a filesystem, and cleanup afterward. This makes tests slow, brittle, and often skipped entirely.

Breaking Dependencies

The solution is to break these dependencies at the seams you've identified. This means replacing concrete implementations with abstractions (interfaces or simple wrappers) that can be swapped out during testing.

Common Strategies

Extract and Override: Pull the dependency into a method you can override in a test subclass. If a method directly opens a file, extract that file-opening logic into its own method.

Parameterize Dependencies: Instead of creating dependencies internally, pass them in as parameters. Rather than new Database() inside your function, accept a database object as an argument.

Replace Global State: Globals and singletons (like Database.getInstance()) are testing nightmares. Wrap them in a parameter or instance variable you control.

Introduce Interfaces: Create an interface for the dependency (like IEmailSender) so you can provide a fake implementation during tests that doesn't actually send emails.

The goal isn't to redesign the entire system—it's to make the smallest change necessary to get tests in place, which then enables safer refactoring.

Key Takeaway: Breaking dependencies means transforming code so you can substitute lightweight, controllable test doubles for heavyweight, unpredictable real dependencies—enabling fast, reliable tests in legacy systems.