Home > Java > javaTutorial > Mockito: `doReturn()` vs. `when()`: When Should You Use Which with Spied Objects?

Mockito: `doReturn()` vs. `when()`: When Should You Use Which with Spied Objects?

Patricia Arquette
Release: 2024-11-28 18:19:15
Original
1036 people have browsed it

Mockito: `doReturn()` vs. `when()`: When Should You Use Which with Spied Objects?

Mockito: Understanding the Subtle Difference between doReturn() and when()

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(...) vs doReturn(...).when(...)

when(...).thenReturn(...):

  • Makes a real method call before returning the specified value.
  • If the called method throws an exception, it must be handled or mocked separately.

doReturn(...).when(...):

  • Avoids the actual method call entirely.

Practical Example

Consider the following MyClass:

public class MyClass {
    protected String methodToBeTested() {
        return anotherMethodInClass();
    }

    protected String anotherMethodInClass() {
        throw new NullPointerException();
    }
}
Copy after login

Testing with Spy

doReturn(...).when(...):

@Spy
private MyClass myClass;

// Works as expected
doReturn("test").when(myClass).anotherMethodInClass();
Copy after login

when(...).thenReturn(...):

// Throws a NullPointerException
when(myClass.anotherMethodInClass()).thenReturn("test");
Copy after login

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!

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