Mockito any()

Introduction

The any() method in Mockito is used to match any value passed to a method. This is particularly useful when you want to verify interactions or stub methods without caring about the exact values of the arguments. This tutorial will demonstrate how to use the any() method in Mockito to handle method arguments.

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 any() method in Mockito to verify and stub methods without caring about the exact argument values.

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.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(MockitoExtension.class)
public class UserServiceTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @Test
    public void testRegisterUser() {
        // Given
        String name = "John Doe";
        String email = "[email protected]";

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

        // Then
        verify(userRepository).saveUser(any(User.class));
    }

    @Test
    public void testGetUserByEmail() {
        // Given
        User user = new User("Jane Doe", "[email protected]");
        when(userRepository.findUserByEmail(anyString())).thenReturn(user);

        // When
        User result = userService.getUserByEmail("[email protected]");

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

Explanation

  1. Creating Mocks with @Mock:

    • The @Mock annotation 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 with @InjectMocks:

    • The @InjectMocks annotation injects the mock UserRepository into the UserService instance to provide a controlled test environment. This allows the UserService methods to be tested in isolation from the actual UserRepository implementation.
  3. Verifying Interactions with any():

    • The verify(userRepository).saveUser(any(User.class)); method checks if the saveUser method was called on the UserRepository with any User object. This ensures that the registerUser method of the UserService class interacts with the UserRepository correctly, without caring about the exact User object passed.
    • The verify(userRepository).findUserByEmail(anyString()); method checks if the findUserByEmail method was called on the UserRepository with any String value. This ensures that the getUserByEmail method of the UserService class interacts with the UserRepository correctly, without caring about the exact email passed.
  4. Stubbing Methods with any():

    • The when(userRepository.findUserByEmail(anyString())).thenReturn(user); method configures the mock UserRepository to return a specific User object when the findUserByEmail method is called with any String value. This allows the getUserByEmail method of the UserService class to be tested with controlled behavior from the UserRepository.

Additional Scenarios

Scenario: Verifying Method Called with Any Argument

In this scenario, we will demonstrate how to verify that a method was called with any argument of a specific type.

@Test
public void testSaveUserWithAnyUser() {
    // Given
    User user = new User("John Doe", "[email protected]");

    // When
    userService.registerUser(user.getName(), user.getEmail());

    // Then
    verify(userRepository).saveUser(any(User.class));
}

Scenario: Stubbing Method with Any Argument

In this scenario, we will demonstrate how to stub a method with any argument of a specific type.

@Test
public void testFindUserByEmailWithAnyString() {
    // Given
    User user = new User("Jane Doe", "[email protected]");
    when(userRepository.findUserByEmail(anyString())).thenReturn(user);

    // When
    User result = userService.getUserByEmail("[email protected]");

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

Conclusion

The any() method in Mockito simplifies the verification and stubbing of method calls on mock objects for unit testing. By using any(), you can handle method arguments flexibly, ensuring that the code under test interacts with its dependencies as expected without caring about the exact values. This step-by-step guide demonstrated how to effectively use the any() 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