Mockito when thenReturn | Java Fresher Interview
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
I'd use when followed by the mock method call, then thenReturn with the value I want to stub.
For example, if I'm testing an OrderService that depends on an OrderRepository, I'd write when orderRepository dot findById one-L dot thenReturn Optional dot of order. This tells Mockito that whenever findById is called with the argument one-L during this test, return that specific order object wrapped in an Optional. The key is doing this in the Arrange phase before I call the service method I'm actually testing.
If I stub it after the service method runs, it's too late and the mock will have already returned null. One thing that confuses freshers is argument matching. If I stub findById with one-L but my service calls it with two-L, the stub won't match and I'll get a null return.
For flexible matching, Mockito provides argument matchers like any or anyLong, so I can write when orderRepository dot findById anyLong then return some default order. You can also chain multiple return values. If I write thenReturn order-one comma order-two, the first call returns order-one and the second call returns order-two.
That's useful for testing loops or retry logic. )is for methods that return values. Void methods use forms such asdoNothing()ordoThrow()`.
)` value.
Mockito when thenReturn | Java Fresher Interview
Direct Answer
Use when(mock.method(args)).thenReturn(value) to configure a mock to return a specific value when that method is called with those arguments. This is the fundamental stubbing pattern in Mockito. Set up the stub in the Arrange phase before executing the code under test.
Code Example
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
private OrderRepository orderRepository;
@InjectMocks
private OrderService orderService;
@Test
void shouldCalculateTotalForExistingOrder() {
var order = new Order(1L, "Laptop", 999.99);
// Arrange: stub the repository method
when(orderRepository.findById(1L))
.thenReturn(Optional.of(order));
// Act: call the service method
var total = orderService.calculateTotal(1L);
// Assert: verify the calculation
assertThat(total).isEqualTo(999.99);
}
}
Common Mistakes & Pitfalls
- Stubbing After Execution: Calling when-thenReturn after the method under test has already executed. The mock returns null during execution, then you stub it—too late. Always stub in the Arrange phase before the Act phase.
- Forgetting Optional Wrapping: Stubbing a repository findById to return an entity directly instead of Optional.of(entity). The method signature returns Optional, so the stub must too, or you get ClassCastException.
- Stubbing the Wrong Mock: Creating multiple mock instances and stubbing one but injecting a different one into the class under test. Use at-Mock and at-InjectMocks annotations to avoid this.
Check your understanding
Answer these without looking back at the article.
- How do you stub a method to throw an exception?
- What is thenAnswer() used for?
- How do you stub consecutive calls to return different values?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.