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
Release: 2024-12-07 14:11:16
Original
386 people have browsed it

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");
Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template