SOLID & Design Patterns Interview Question #140
How can design patterns improve testability?
Anti-Patterns, Refactoring, DI Lifetimes & Senior Design Scenarios Senior Advanced
Quick Interview Answer
Patterns can improve testability when they isolate side effects and introduce meaningful seams. Strategy can make algorithms replaceable, Adapter can isolate external APIs, and Dependency Injection can supply test doubles for infrastructure collaborators.
Detailed Explanation
Patterns can improve testability when they isolate side effects and introduce meaningful seams. Strategy can make algorithms replaceable, Adapter can isolate external APIs, and Dependency Injection can supply test doubles for infrastructure collaborators.
Patterns do not automatically create good tests. Excessive abstractions can make tests tightly coupled to implementation structure. Test behavior at useful boundaries rather than mocking every internal method.
Code Example
var gateway = new FakePaymentGateway();
var service = new CheckoutService(gateway);
await service.CheckoutAsync(order);
Assert.True(gateway.WasCharged);