Java Testing with Mockito & Assertj

(, en)

I always forget them. Usually no problem, because you have plenty of examples in your current project. But what if you change clients?

Dependencies

Documentation

Junit5 & Mockito

@ExtendWith(MockitoExtension.class)
public class MonkeyServiceTest {
  
  @Mock(answer = Answers.RETURNS_SMART_NULLS)
  ForestService forestService;

  @InjectMocks
  MonkeyService monkeyService;

  @Spy
  Config config = ConfigFactory.load();
  
  // capture args for classes with nested type parameters
  @Captor
  ArgumentCaptor<List<Monkey>> monkeyCaptor;

  @Test
  @SneakyThrows
  void shouldEatBanana() {

    // void with retrieving temp file contents
    ArrayList<String> content = new ArrayList<>();
    doAnswer(i -> {
      Path f = i.getArgument(1, Path.class);
      content.add(TestFileUtil.getFileContent(f));
      return null;
    }).when(forestService).write(any(), any());

    when(forestService.setArea(any(AreaRequest.class), any())).then(invocation -> {
          // ...
          return null;
        }
    );
    final ArgumentCaptor<String> contentCaptor = ArgumentCaptor.forClass(String.class);
    final ArgumentCaptor<String> treeCaptor = ArgumentCaptor.forClass(String.class);
    monkeyService.eatAll();
    verify(forestService, times(1)).shakeTree(treeCaptor.capture(), contentCaptor.capture());
  }
  // ...
}

Assert exceptions

import static org.assertj.core.api.Assertions.assertThatThrownBy;

assertThatThrownBy(() -> monkeyService.getMonkey(id)).isInstanceOf(NoRainforestException.class);

Assert static methods

Activate required Mockito extension:

mkdir -p src/test/resources/mockito-extensions
echo mock-maker-inline > src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker

In the test:

try (MockedStatic<TimeProvider> mockedTimeProvider = mockStatic(TimeProvider.class)) {
  mockedTimeProvider
    .when(TimeProvider::now)
    .thenReturn(LocalDateTime.of(2000, 1, 1, 1, 1, 1));
  
  //...
}