Using the Existing Argument Matchers

The ProjectService class from Chapter 2, Work with the Mockito API, contains a method called findByIds(int...). That method in turn calls the findById(int) method on the PersonRepository, which we needed to mock to isolate our PersonService for testing. Here’s a test of the service method for the case where the requested ID doesn’t exist in the database:

 @Test
 public​ ​void​ ​findByIdThatDoesNotExist​() {
  when(repository.findById(anyInt()))
  .thenReturn(Optional.empty());
 
  List<Person> personList = service.findByIds(999);
  assertTrue(personList.isEmpty());
 
  verify(repository).findById(anyInt());
 }

The anyInt method was used both when setting the expectations and when verifying ...

Get Mockito Made Clear 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.