Chapter 17. Mocks to Maps
Mocks are a common technique to decouple object-oriented code from its production dependencies. Are better solutions available in Kotlin?
This is a short bonus chapter, following on from Chapter 16.
In that chapter, we saw that our tests used mocks because they had to implement two multimethod interfaces, even though most of those methods were not used.
We left the refactoring, having replaced dependencies on multimethod interfaces with a dependency on just the two operations that were actually required to perform the task.
The tests, though, still mock the whole interface, and then pass a reference to the required methods to the subject under test (Recommendations):
publicclassRecommendationsTests{privatefinalDistanceCalculatordistanceCalculator=mock(DistanceCalculator.class);privatefinalFeaturedDestinationsfeaturedDestinations=mock(FeaturedDestinations.class);privatefinalRecommendationsrecommendations=newRecommendations(featuredDestinations::findCloseTo,distanceCalculator::distanceInMetersBetween);...}
The tests abstract the mocking behind methods givenFeaturedDestinationsFor and givenADistanceBetween:
@Testpublicvoidreturns_recommendations_for_single_location(){givenFeaturedDestinationsFor(paris,List.of(eiffelTower,louvre));givenADistanceBetween(paris,eiffelTower,5000);givenADistanceBetween(paris ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access