Mockito.doReturn() Example

1. Introduction

One of the powerful features of Mockito is the ability to control the behavior of a mocked method. The doReturn() method allows you to set a specific return value or exception when a mocked method is called. This approach is particularly useful when dealing with void methods or when spying on real objects.

2. Example Steps

1. Create an interface with a method to fetch a username.

2. Provide a concrete implementation of this interface.

3. Set up a test class.

4. Mock the interface with Mockito.

5. Use the doReturn() method to stub the return value of the mocked method.

6. Execute the test and verify the stubbed value.

3. Mockito.doReturn() Example

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;

// Step 1: Define an interface
interface UserService {
    String fetchUserName();
}

// Step 2: Concrete implementation of the interface
class RealUserService implements UserService {
    @Override
    public String fetchUserName() {
        return "John";
    }
}

public class UserServiceTest {

    @Test
    public void testDoReturnWithMockito() {
        // Step 4: Mock the UserService interface
        UserService mockedUserService = mock(UserService.class);

        // Step 5: Use doReturn() to stub the return value of fetchUserName()
        doReturn("MockedUser").when(mockedUserService).fetchUserName();

        // Execute and print the stubbed value
        System.out.println(mockedUserService.fetchUserName());
    }
}

Output:

MockedUser

4. Step By Step Explanation

1. We begin by defining a UserService interface that has a method to fetch a username.

2. The RealUserService provides an actual implementation, returning the username "John". This is the behavior in the real-world scenario.

3. In the UserServiceTest class, we mock the UserService interface to test its behavior.

4. Instead of the actual implementation, we wish to control what the fetchUserName() method returns. For this, we use Mockito's doReturn() method. We stub the method to return "MockedUser" instead of "John".

5. When we call fetchUserName() on the mock during the test, it returns the stubbed value "MockedUser" instead of "John".

6. This ability to control the return values of methods makes unit testing more effective, as we can test for various scenarios by manipulating what our methods return.


Comments