Home >Java >javaTutorial >Mockito Mocking: When() vs. doReturn() – When Should I Use Which?

Mockito Mocking: When() vs. doReturn() – When Should I Use Which?

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 14:11:16385browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn