Home >Java >javaTutorial >Mockito: `doReturn()` vs. `when()` – When Should I Use Which for Mocking?
Mockito - Exploring the Distinction Between doReturn() and when() for Mocking
When harnessing Mockito's power in a Spring MVC application, developers often encounter the similarity between doReturn(...).when(...) and when(...).thenReturn(...). This sparks the question of why these two methods exist, given their apparent equivalence.
While both approaches yield the same outcome with mocks annotated with @Mock, a subtle difference emerges when using spied objects annotated with @Spy. Unlike when(...).thenReturn(...), which executes the actual method call before returning the specified value, doReturn(...) bypasses the method call entirely.
This distinction becomes crucial when dealing with spied objects that have methods that throw exceptions. For instance, consider the following class with two methods:
public class MyClass { protected String methodToBeTested() { return anotherMethodInClass(); } protected String anotherMethodInClass() { throw new NullPointerException(); } }
In the test class:
@Spy private MyClass myClass; // ... // Executes methodToBeTested() and swallows the NullPointerException doReturn("test").when(myClass).anotherMethodInClass(); // Throws NullPointerException without executing methodToBeTested() when(myClass.anotherMethodInClass()).thenReturn("test");
As demonstrated, doReturn(...) allows you to control the return value without triggering method execution, while when(...) executes the method first and only then provides the specified result. This subtle difference enables greater control over object mocking and exception management, making doReturn(...) the preferred choice when dealing with spied objects that may throw exceptions.
The above is the detailed content of Mockito: `doReturn()` vs. `when()` – When Should I Use Which for Mocking?. For more information, please follow other related articles on the PHP Chinese website!