0

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?

  • For starters, there's no point in mocking values like `Calendar`; just use a real one. Furthermore, you don't seem to be testing `fetch` but rather `fetch2`. – chrylis -cautiouslyoptimistic- Sep 11 '21 at 02:36
  • @chrylis-cautiouslyoptimistic-, firstly thanks for your comment. Calendar is my Object, It doesn't come from the java.util. Then, fetch 2 is my typo mistake. – Phuong Tran Sep 11 '21 at 03:14

1 Answers1

3

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());
}
SKumar
  • 1,940
  • 1
  • 7
  • 12