Unsing Java's Supplier interface to facilitate mock behavior for unit tests

555 views Asked by At

I recently had to refactor a class [X] and improve its unit test and in doing so discovered that in order to get full coverage of the class from the tests I was going to need to mock out the behaviour of 3 different components of the class. For arguments sake classes [A], [B] and [C]. Because [A], [B] & [C] were all constructed within [X] I decided to pass in a Supplier for each of them allowing the unit test to mock the Supplier and enable complete test coverage of the class.

However a colleague of mine suggested instead that I could have added package visible getter methods for each of [A], [B] & [C] to deal with the object construction and then override these from the unit test when creating the instance of [X] to be tested.

I can see that this removes the extra complication of adding the Supplier implementations but I feel this exposes the implementation of [X] unnecessarily. Is one of these approaches considered to substantially better than the other? The project I'm working on uses Spring which I'm not too familiar with, but I'm wondering if there might be a better solution with that.

Does anyone have some solid advice on this?

0

There are 0 answers