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: • The pattern is when(mock.method(args)).thenReturn(value); - it records the stub before the method under test runs. • Chaining multiple thenReturn() calls, e.g. thenReturn(a, b), makes successive calls return different values in sequence. • Argument matchers like any() or eq() inside when() control which invocations the stub applies to. • when()...thenReturn() only works for non-void methods; void methods need doReturn()/doNothing() patterns instead. • Unstubbed methods on a mock return sensible defaults (null, 0, false, empty collection) rather than throwing.
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.
Code Example:
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."