Video in progress
Why does a classic Singleton make code hard to test?
An object obtained through a static getInstance() can't be swapped in a test, its state persists between tests, and the tests affect each other. Because the dependency is hidden, it also isn't visible from the class signature.
📖 Answer
public class InvoiceService {
public Invoice create(Order o) {
var rate = CurrencyClient.getInstance().rate("USD"); // external API
return new Invoice(o.total().multiply(rate));
}
}
You want to unit test this method, but every time a request goes to the real currency API. There's no place to put a mock: CurrencyClient doesn't come in through the constructor, it's obtained inside with a static call.
Two more problems:
- If the Singleton holds state (a cache, a counter), the first test changes it and the second test starts from a different state. Tests pass or fail depending on their order.
- In parallel tests it's even more confusing.
The fix is to make the dependency explicit:
public class InvoiceService {
private final RateProvider rates;
public InvoiceService(RateProvider rates) { this.rates = rates; }
}
Now in a test new InvoiceService(currency -> BigDecimal.TEN) is enough. In prod Spring gives one instance, so the "uniqueness" is kept, but it isn't baked into the class. Mockito has mockStatic, but it's a temporary patch, not a design solution.
Sign up to mark studied questions and save your progress.