Home >Java >javaTutorial >Mockito Mocking: When() vs. doReturn() – When Should I Use Which?
Utilizing Mockito: DoReturn() vs. When()
In the realm of Mockito, two methods emerge with apparent similarities: doReturn() and when(). Both facilitate object mocking functionalities, prompting the query: why the need for two such analogous methods?
The answer lies in their behavior when used with spied objects (annotated with @Spy) versus mocked objects (annotated with @Mock). Unlike mocked objects, spied objects retain the actual method implementations of the class they extend.
When() thenReturn() calls the original method before substituting the specified return value. Consequently, exceptions thrown by the method must be handled within the test. For example:
@Spy private MyClass myClass; // Continues executing the actual method, potentially throwing an exception when(myClass.anotherMethodInClass()).thenReturn("test");
DoReturn() when(), on the other hand, intercepts the method call altogether. This prevents the original method from executing and eliminates the risk of exceptions:
// Bypasses the actual method call, returning the specified value doReturn("test").when(myClass).anotherMethodInClass();
Understanding this distinction is crucial when working with spied objects. In situations where the spied method might trigger errors, doReturn() offers a safe alternative to when(), ensuring a smooth testing experience.
The above is the detailed content of Mockito Mocking: When() vs. doReturn() – When Should I Use Which?. For more information, please follow other related articles on the PHP Chinese website!