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

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

Linda Hamilton
Release: 2024-12-09 16:01:16
Original
1003 people have browsed it

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

Mockito - Exploring the Distinction Between doReturn() and when() for Mocking

When harnessing Mockito's power in a Spring MVC application, developers often encounter the similarity between doReturn(...).when(...) and when(...).thenReturn(...). This sparks the question of why these two methods exist, given their apparent equivalence.

While both approaches yield the same outcome with mocks annotated with @Mock, a subtle difference emerges when using spied objects annotated with @Spy. Unlike when(...).thenReturn(...), which executes the actual method call before returning the specified value, doReturn(...) bypasses the method call entirely.

This distinction becomes crucial when dealing with spied objects that have methods that throw exceptions. For instance, consider the following class with two methods:

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

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

In the test class:

@Spy
private MyClass myClass;

// ...

// Executes methodToBeTested() and swallows the NullPointerException
doReturn("test").when(myClass).anotherMethodInClass();

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

As demonstrated, doReturn(...) allows you to control the return value without triggering method execution, while when(...) executes the method first and only then provides the specified result. This subtle difference enables greater control over object mocking and exception management, making doReturn(...) the preferred choice when dealing with spied objects that may throw exceptions.

The above is the detailed content of Mockito: `doReturn()` vs. `when()` – When Should I Use Which for Mocking?. 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