When utilizing the mocking framework Mockito to enhance testing capabilities, developers often encounter the doReturn() and when() methods. While both methods serve the purpose of stubbing method invocations, a subtle distinction lies between them when working with spied objects (annotated with @Spy).
when(...).thenReturn(...):
doReturn(...).when(...):
Consider the following MyClass:
public class MyClass { protected String methodToBeTested() { return anotherMethodInClass(); } protected String anotherMethodInClass() { throw new NullPointerException(); } }
doReturn(...).when(...):
@Spy private MyClass myClass; // Works as expected doReturn("test").when(myClass).anotherMethodInClass();
when(...).thenReturn(...):
// Throws a NullPointerException when(myClass.anotherMethodInClass()).thenReturn("test");
In this scenario, doReturn() ensures that the exception in anotherMethodInClass() is avoided while still returning the desired value. In contrast, when() triggers the actual method call, resulting in the NullPointerException being thrown.
Therefore, when working with spied objects, the choice between doReturn() and when() depends on whether you want to invoke the actual method or bypass it altogether.
The above is the detailed content of Mockito: `doReturn()` vs. `when()`: When Should You Use Which with Spied Objects?. For more information, please follow other related articles on the PHP Chinese website!