Video in progress
If a class is hard to unit test, what design problems does that point to, and how do you fix them?
Usually hidden dependencies: services created with new inside the class, static calls, LocalDateTime.now(), singletons. If you turn them into dependencies passed through the constructor, testing gets easy and the design improves too.
📖 Answer
A class that can't be tested:
public class SubscriptionService {
public void renewExpired() {
var repo = new JdbcSubscriptionRepo(DataSourceHolder.get()); // hidden
for (var s : repo.findAll()) {
if (s.getEndsAt().isBefore(LocalDateTime.now())) { // time is frozen in
PaymentClient.getInstance().charge(s.getUserId(), s.getPrice()); // singleton
s.setEndsAt(s.getEndsAt().plusDays(31));
repo.save(s);
}
}
}
}
What is wrong:
new JdbcSubscriptionRepowon't run without a DB;LocalDateTime.now(): you can't test the "expired" case, and the test depends on time;- a static singleton: you need
mockStaticto mock it, which is a signal; findAll()+ a filter in Java: the business rule and the query are mixed together.
The fixed version:
public class SubscriptionService {
private final SubscriptionRepository repo;
private final PaymentGateway payments;
private final Clock clock;
// constructor injection: all the dependencies are visible
public void renewExpired() {
var now = Instant.now(clock);
for (var s : repo.findExpiredAt(now)) {
payments.charge(s.userId(), s.price());
s.renew(); // the 31-day rule is in the domain object
repo.save(s);
}
}
}
In the test: Clock.fixed(...), an in-memory repository and a fake PaymentGateway.
A general rule: if the number of mocks in a test grows, or you need mockStatic, reflection or @PrepareForTest, the code is the problem, not the test. Testability is a side effect of good design, not a separate goal.
Sign up to mark studied questions and save your progress.