Here is my implementation:
List<Calendar> fetch(String input) { return Optional.ofNullable(input) .map(client::getCalendars) .orElse(repository.fetch()); }
And the test:
@Test void fetchGetsDataFromHolidayClient() { //Given String input = "search by post code or city"; List<Calendar> expected = singletonList(mock(Calendar.class)); doReturn(expected).when(client).getCalendars(input); // When List<Calendar> actual = service.fetch(input); // Then verify(client).getCalendars(input); verify(repository, never()).fetch(); assertThat(expected).isEqualTo(actual); }
Test failed the result below:
Never wanted here: -> at ServiceTest.fetchGetsDataFromHolidayClient(ServiceTest.java:57) But invoked here: -> at Service.fetch(Service.java:39)
Calendar is my POJO, It isn’t java.util.Calendar! I used Oracle JK 8, Junit5. Is this a bug of mockito?
Advertisement
Answer
It’s not a bug but rather the orElse
is evaluated when the optional has a non null value.
You need orElseGet
. So, repository call will be made only when needed. –
List<Calendar> fetch(String input) { return Optional.ofNullable(input) .map(client::getCalendars) .orElseGet(() -> repository.fetch()); }