Home >Java >javaTutorial >Mockito\'s doReturn() vs. when(): What\'s the Difference When Using Spied Objects?
Understanding the Distinction between Mockito's doReturn() and when()
While developing Spring MVC applications, the use of Mockito to mock service layer objects is a common practice. While exploring Mockito's capabilities, it becomes evident that both doReturn(...).when(...) and when(...).thenReturn(...) appear to perform the same function. This begs the question: is there any difference between these two methods?
The key distinction between doReturn() and when() becomes apparent when using spied objects (annotated with @Spy) instead of mocks (annotated with @Mock).
doReturn() vs. when() with Spied Objects
Example
Consider the following code:
public class MyClass { protected String methodToBeTested() { return anotherMethodInClass(); } protected String anotherMethodInClass() { throw new NullPointerException(); } }
Test Case:
@Spy private MyClass myClass; // Works fine, does not invoke anotherMethodInClass() doReturn("test").when(myClass).anotherMethodInClass(); // Throws NullPointerException because anotherMethodInClass() is invoked when(myClass.anotherMethodInClass()).thenReturn("test");
In summary, when using spied objects, doReturn() allows you to skip method execution and directly set the return value, while when() invokes the actual method prior to returning the desired value. This understanding is crucial when working with spied objects in Mockito.
The above is the detailed content of Mockito\'s doReturn() vs. when(): What\'s the Difference When Using Spied Objects?. For more information, please follow other related articles on the PHP Chinese website!