Mocking Constructors
So far, we’ve been lucky because every time we wanted to mock a dependency of a class under test, we had an easy way to insert the mock into the class. Most of the time, we’ve used constructors for this purpose, like when we injected a mock of the PersonRepository into the PersonService to test the service.
Of course, this wasn’t luck at all; the applications were designed with constructors like that in mind. But what if they weren’t? What if we had a class that instantiated a dependency as a local variable? How would we mock that?
Back in Chapter 1, Build a Testing Foundation, we looked at a class called HelloMockito, which had two dependencies: a PersonRepository and a TranslationService. Here’s a reminder:
Get Mockito Made Clear now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.