Video in progress

Junior 🧪 Testing

In Mockito, what actually happens when you write when(...).thenReturn(...)?

The call inside when is "recorded" on the mock, and thenReturn sets what later calls with those arguments will return. Calls you haven't stubbed return a default value: null, 0, false, or an empty collection.

📖 Answer

UserRepository repo = mock(UserRepository.class);

when(repo.findById(1L)).thenReturn(Optional.of(new User(1L, "Aziz")));

repo.findById(1L);   // Optional[User Aziz]
repo.findById(2L);   // Optional.empty: Mockito returns empty for Optional
repo.count();        // 0

Stubbing depends on the argument: if you stubbed it for 1L, it doesn't apply to 2L. For any argument use any() or anyLong().

You can also return different answers in sequence:

when(gateway.charge(any()))
    .thenThrow(new ResourceAccessException("1-urinish: timeout"))   // unchecked; Mockito errors if a checked exception isn't in the method signature
    .thenReturn(PaymentResult.ok());

This is very handy for testing retry logic: the first call fails, the second succeeds.

thenAnswer is for when the answer has to be computed from the arguments, for example when you want save to return the object it was given.