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
):
public
class
RecommendationsTests
{
private
final
DistanceCalculator
distanceCalculator
=
mock
(
DistanceCalculator
.
class
);
private
final
FeaturedDestinations
featuredDestinations
=
mock
(
FeaturedDestinations
.
class
);
private
final
Recommendations
recommendations
=
new
Recommendations
(
featuredDestinations:
:
findCloseTo
,
distanceCalculator:
:
distanceInMetersBetween
);
...
}
The tests abstract the mocking behind methods givenFeaturedDestinationsFor
and givenADistanceBetween
:
@Test
public
void
returns_recommendations_for_single_location
()
{
givenFeaturedDestinationsFor
(
paris
,
List
.
of
(
eiffelTower
,
louvre
));
givenADistanceBetween
(
paris
,
eiffelTower
,
5000
);
givenADistanceBetween
(
paris ...
Get Java to Kotlin 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.