How do you use when and thenReturn in Mockito?

when() and thenReturn() are chained together in Mockito to define what value a mocked method should return when it's called with matching arguments.

Key Points

Example

Stubbing when(userRepository.findById(1L)).thenReturn(Optional.of(testUser)) makes the repository mock return a specific test user whenever findById(1L) is called during the test.

UserRepository repo = mock(UserRepository.class);
when(repo.findById(1L)).thenReturn(Optional.of(new User("Alice")));

Optional<User> result = repo.findById(1L);
assertEquals("Alice", result.get().getName());

Interview Tip

A concise interview answer is

when(mock.method(args)).thenReturn(value) tells Mockito what to return the next time that method is called with matching arguments. I use it to set up predictable dependency behavior before invoking the method under test, and chain multiple values when I need different results on successive calls.

Last updated: 16 July 2026

Previous question: What is the purpose of the @Mock and @InjectMocks annotations?

Next question: What is the difference between mock() and spy() in Mockito?

More Mockito interview questions

All Mockito questions