How to Use Mockito’s any() Matcher for Flexible Argument Matching

Master Mockito's any() matcher to handle dynamic arguments and improve test flexibility. Test your application on real devices to verify behavior across scenarios.

Get Started free
How to Use Mockito’s any() Matcher for Flexible Argument Matching
Home Guide How to Use Mockito’s any() Matcher for Flexible Argument Matching

How to Use Mockito’s any() Matcher for Flexible Argument Matching

When testing Java code, real dependencies like databases or APIs can slow down tests or make them unreliable. To avoid this, Mockito allows you to mock dependencies and isolate unit tests. The Mockito any() matcher helps verify method calls and stub behaviors without requiring exact argument values.

This guide explains the Mockito’s any() matcher and how to use it effectively.

What is Mockito: Quick Overview

Mockito is a Java mocking framework used in unit testing to simulate dependencies. It allows you to mock objects without relying on databases or backend services, making tests faster and more isolated.

It supports features like stubbing, verification, and argument matchers. Developers commonly use Mockito in unit tests to verify the behavior of a component or service in isolation.

What is Mockito’s any() matcher?

The any() method in Mockito is a flexible argument matcher that allows method calls to accept any value of a specific type. It helps with stubbing and verification in unit tests by enabling generic test cases that do not require exact argument values. This is useful when working with dynamic inputs or when the exact values are unknown.

Why Use Mockito any()?

Mockito’s any() method allows flexible and reliable unit tests without creating dependency on specific argument values. Here are some reasons to use Mockito any().

1. Flexible Argument Matching

It provides flexible argument matching. Instead of verifying the exact values, you can specify the values of a specific type. This is helpful when you want to test the behavior with multiple different values of a Specific type.

verify(mockRepo).saveUser(anyString());
Copied

The above code matches any string value, and it is not restricted to specific values.

2. Simplifies Testing

Without any() matcher, you might have to write many tests to cover all permutations and combinations with exact value matcher. The any() matchers simplify testing by dynamically accepting any values for verifications. Additionally, any() focuses on input behavior, and with Mockito, it reduces any delicacies in the code.

when(mockRepo.getUserRole(anyString())).thenReturn("ViewOnly");
Copied

The above method always returns the ViewOnly role if the argument type is a string.

When should you use an argument matcher?

Use an argument matcher when inputs are unpredictable, vary across test cases, or are irrelevant to the test’s purpose. This is helpful when dealing with dynamic user input, API responses, or time-sensitive values like timestamps or generated IDs.

Argument matchers also simplify testing when verifying method calls matter more than the exact argument values, such as logging or event tracking scenarios.

BrowserStack Automate Banner

Common Variants of Mockito any()

The Mockito framework provides any() method with many variants that help handle different data types. These matchers help write flexible assertions and more generic tests.

  • any(): Matches any object of any type. It is useful when the method can accept different object types. The method parameter can be the object of any class.

Example:

verify(mockRepo).saveUser(any(User.class));
Copied
  • anyString(): This method matches any string. It is useful when input values are unpredictable or dynamic. The method parameter can be a string.

Example:

when(mockRepo.getUserRole(anyString())).thenReturn("ViewOnly")
Copied
  • anyInt(): This method matches any integer. It is used for methods that process numeric IDs, counts, or flags, and the method parameter can be an integer.

   Example:

when(mockService.processOrder(anyInt())).thenReturn("Complete");
Copied
  • anyLong(): This method matches any long value. It is often used for database IDs or timestamps.

Example:

verify(mockRepo).getUserID(anyLong()).thenReturn("9990493033");
Copied
  • anyDouble(): This method matches any long value. It is helpful for calculations or percentage-based logic.

   Example: 

when(mockCalculator.getDiscount(anyDouble())).thenReturn(19.0);
Copied
  • anyBoolean(): This method matches any boolean value. It is commonly used for feature flags or conditions.

Example:

when(mockFeature.isEnabled (anyBoolean())).thenReturn(true);
Copied
  • Collection Matchers

The any() also supports collection matches such as anyList(), anySet(), and anyMap(). You can match entire collections without checking their contents. It is useful when the method processes lists, sets, or maps of varying sizes and values.

Example:

when(mockRepo.processUsers(anyList())).thenReturn("Success");
Copied

How to add Mockito to JUnit 5?

Considering you have a Java Maven Project, you need to add the dependencies to your project to enable Mockito with JUnit 5.

1. Add JUnit 5 Dependency

This is a core JUNit dependency for writing JUnit 5 test cases

<dependency>

    <groupId>org.junit.jupiter</groupId>

    <artifactId>junit-jupiter-api</artifactId>

    <scope>test</scope>

</dependency>
Copied

2. Add Mockito Core Dependency

This is a core dependency for Mockito. It allows you to create and use mock objects. Additionally, this library provides methods to mock or stub the classes, such as when(), verify(), etc.

<dependency>

    <groupId>org.mockito</groupId>

    <artifactId>mockito-core</artifactId>

    <version>5.5.0</version>

    <scope>test</scope>

</dependency>
Copied

3. Add Mockito JUnit 5 Integration Dependency

This dependency helps integrate Junit 5 with Mockito seamlessly and enables automatic mock initialization.

<dependency>

    <groupId>org.mockito</groupId>

    <artifactId>mockito-junit-jupiter</artifactId>

    <version>5.5.0</version>

    <scope>test</scope>

</dependency>
Copied

How to Use Mockito’s any() matcher?

This section provides practical examples of using the any() matcher in Mockito. These examples will help you write flexible and maintainable tests.

1. UserService and UserRepository Classes

The UserService and UserRepository classes follow a standard service-repository pattern in Java applications. UserService contains business logic, while UserRepository handles data storage and retrieval.

When testing UserService, making real database calls can slow down tests and introduce dependencies on external systems. Instead, Mockito allows mocking UserRepository so that tests focus only on service logic. The any() matcher helps handle scenarios where method inputs are unpredictable.

UserRepository Interface

The UserRepository interface defines data operations related to user management.

Example:

package users;

public interface UserRepository {

    User findUserById(String id);

    void saveUser(User user);

}
Copied

This interface specifies methods for retrieving and saving user data in the above code.

UserService Class: The UserService class contains business logic and interacts with UserRepository.

Example:

package users;

public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {

        this.userRepository = userRepository;

    }

    public User getUser(String id) {

        return userRepository.findUserById(id);

    }

    public void registerUser(User user) {

        userRepository.saveUser(user);

    }

}
Copied

In the above code, UserService is a business layer that provides many methods to perform operations, such as getUser() and registerUser().

User Class

The User class represents a user entity with attributes such as ID and name.

Example:

package users;

public class User {

    private String id;

    private String name;

    public User(String id, String name) {

        this.id = id;

        this.name = name;

    }

    public String getId() { return id; }

    public String getName() { return name; }

}
Copied

This class defines the structure of a user entity with ID and name properties.

2. JUnit 5 Test Class with Mockito

As you have defined the User, UserService, and UserRepository Classes, you can write the Junit5 classes with Mockito.

import static org.mockito.Mockito.*;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.BeforeEach;

import org.junit.jupiter.api.Test;

import org.mockito.Mock;

import org.mockito.MockitoAnnotations;

import users.User;

import users.UserRepository;

import users.UserService;

public class UserServiceTest {

    @Mock

    private UserRepository userRepository; 

    private UserService userService;

    @BeforeEach

    void setUp() {

        MockitoAnnotations.openMocks(this);

        userService = new UserService(userRepository);

    }

}
Copied

In the above code, you are mocking the dependencies with code private UserRepository mockRepository using the Junit 5 Mockito integration.

3. Verifying Method Called with any() Argument

Mockito’s any() matcher helps verify that a method was called with an argument of a specified type, regardless of the actual value. This is useful when the exact input is unpredictable or irrelevant to the test.

Example:

@Test

void testRegisterUserAnyUser() {

    User user = new User("2494", "BrowserStackUser2");

    userService.registerUser(user);

    verify(userRepository).saveUser(any(User.class));

}
Copied

In the above code, a new User object is created and passed to the registerUser() method. The test then verifies that the saveUser() method was called with any instance of User, using any(User.class). This ensures the method is invoked as expected without requiring an exact match on the user object.

4. Stubbing Methods with any()

Stubbing allows tests to control method behavior by returning predefined values when certain arguments match. Mockito’s any() matcher ensures flexibility by allowing a method to return a result for any input of a specified type.

Example:

    @Test

    void testStubbingWithAny() {

        when(userRepository.findUserById(any(String.class)))

                .thenReturn(new User("99872", "BrowserStackUser4"));

        User user = userService.getUser("randomId");

        assertEquals("BrowserStackUser4", user.getName());

    }
Copied

In the above code, the when() method stubs the findUserById() method to return a specific User object whenever it receives any String as an argument. The test calls the getUser() method with a random ID, and since findUserById() is stubbed, it returns a user with the ID “99872” and the name “BrowserStackUser4”. The assertion verifies that the expected user name is returned.

Talk to an Expert

Conclusion

Mockito’s any() matcher allows flexible verification and stubbing by matching arguments dynamically. This helps write reliable and maintainable tests without depending on specific input values. However, unit tests alone are not enough. Real-world conditions affect functionality and make real device testing essential for accurate validation.

BrowserStack provides instant access to 3,500+ real devices to ensure applications work as expected across different environments. With BrowserStack, you can verify app behavior beyond mocked scenarios and ensure APIs, databases, and UI interactions function correctly across multiple device-OS combinations without maintaining an in-house device lab.

Try BrowserStack Now

Tags
Automation Testing Mobile App Testing Real Device Cloud Testing Tools