Mockito mock()

Introduction

The mock() method in Mockito is used to create mock objects for unit testing. Mock objects simulate the behavior of real objects in a controlled way, allowing you to isolate the code under test. This tutorial will demonstrate how to use the mock() method in Mockito to create and configure mock objects.

Maven Dependencies

To use Mockito with JUnit 5, add the following dependencies to your pom.xml file:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>4.8.1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>4.8.1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.9.2</version>
    <scope>test</scope>
</dependency>

Example Scenario

We will create a UserService class that has a dependency on a UserRepository. Our goal is to test the UserService methods using the mock() method in Mockito to create mock objects for the dependencies.

UserService and UserRepository Classes

First, create the User class, the UserRepository interface, and the UserService class.

public class User {
    private String name;
    private String email;

    // Constructor, getters, and setters
    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

public interface UserRepository {
    void saveUser(User user);
    User findUserByEmail(String email);
}

public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void registerUser(String name, String email) {
        User user = new User(name, email);
        userRepository.saveUser(user);
    }

    public User getUserByEmail(String email) {
        return userRepository.findUserByEmail(email);
    }
}

JUnit 5 Test Class with Mockito

Create a test class for UserService using JUnit 5 and Mockito.

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

public class UserServiceTest {

    @Test
    public void testRegisterUser() {
        // Create a mock UserRepository
        UserRepository userRepository = mock(UserRepository.class);

        // Create a UserService with the mock UserRepository
        UserService userService = new UserService(userRepository);

        // Given
        String name = "John Doe";
        String email = "[email protected]";

        // When
        userService.registerUser(name, email);

        // Then
        ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
        verify(userRepository).saveUser(userCaptor.capture());
        User capturedUser = userCaptor.getValue();
        assertEquals(name, capturedUser.getName());
        assertEquals(email, capturedUser.getEmail());
    }

    @Test
    public void testGetUserByEmail() {
        // Create a mock UserRepository
        UserRepository userRepository = mock(UserRepository.class);

        // Create a UserService with the mock UserRepository
        UserService userService = new UserService(userRepository);

        // Given
        String email = "[email protected]";
        User mockUser = new User("Jane Doe", email);
        when(userRepository.findUserByEmail(email)).thenReturn(mockUser);

        // When
        User result = userService.getUserByEmail(email);

        // Then
        assertNotNull(result);
        assertEquals("Jane Doe", result.getName());
        assertEquals(email, result.getEmail());
        verify(userRepository).findUserByEmail(email);
    }
}

Explanation

  1. Creating Mocks with mock():

    • The mock(UserRepository.class) method creates a mock instance of the UserRepository interface.
    • This mock instance can be used to simulate the behavior of the UserRepository in a controlled way.
  2. Injecting Mocks:

    • The mock UserRepository is injected into the UserService constructor to provide a controlled test environment.
    • This allows the UserService methods to be tested in isolation from the actual UserRepository implementation.
  3. Configuring Mock Behavior:

    • The when(userRepository.findUserByEmail(email)).thenReturn(mockUser) method configures the mock UserRepository to return a predefined User object when the findUserByEmail method is called with the specified email.
  4. Verifying Interactions:

    • The verify(userRepository).saveUser(userCaptor.capture()) method verifies that the saveUser method was called on the UserRepository with a User object.
    • The ArgumentCaptor captures the User object passed to the saveUser method, allowing for further assertions on its properties.
    • The verify(userRepository).findUserByEmail(email) method verifies that the findUserByEmail method was called on the UserRepository with the specified email.

Conclusion

The mock() method in Mockito simplifies the creation of mock objects for unit testing. By using mock(), you can easily simulate dependencies and test the behavior of your code in isolation. This step-by-step guide demonstrated how to effectively use the mock() method in your unit tests, covering different scenarios to ensure comprehensive testing of the UserService class.

Related Mockito Methods

Mockito mock()
Mockito spy()
Mockito when()
Mockito thenThrow()
Mockito verify()
Mockito times()
Mockito never()
Mockito any()
Mockito eq()
Mockito inOrder()
Mockito doReturn()
Mockito doThrow()
Mockito doAnswer()
Mockito timeout()
Mockito ArgumentMatchers

Comments