0
0
JUnittesting~5 mins

Argument matchers (any, eq) in JUnit

Choose your learning style9 modes available
Introduction

Argument matchers help you check if a method was called with certain values during testing. They make tests flexible and clear.

When you want to verify a method was called with any value of a certain type.
When you want to check a method was called with an exact value.
When you want to avoid writing many tests for different input values.
When you want to simplify tests by ignoring some arguments.
When you want to combine exact and flexible checks in one test.
Syntax
JUnit
verify(mockObject).methodName(any(Type.class));
verify(mockObject).methodName(eq(expectedValue));

any(Type.class) matches any value of the given type.

eq(value) matches exactly the given value.

Examples
This checks if createUser was called with any String value.
JUnit
verify(userService).createUser(any(String.class));
This checks if createUser was called exactly with the string "Alice".
JUnit
verify(userService).createUser(eq("Alice"));
This checks if placeOrder was called with order ID 123 and any integer quantity.
JUnit
verify(orderService).placeOrder(eq(123), any(Integer.class));
Sample Program

This test class mocks UserService. The first test checks if createUser was called with any string. The second test checks if it was called with the exact string "Alice".

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

class UserService {
    void createUser(String name) {
        // Imagine user creation logic here
    }
}

public class UserServiceTest {
    @Test
    void testCreateUserCalledWithAnyName() {
        UserService mockUserService = mock(UserService.class);

        mockUserService.createUser("Bob");

        // Verify method called with any String
        verify(mockUserService).createUser(any(String.class));
    }

    @Test
    void testCreateUserCalledWithExactName() {
        UserService mockUserService = mock(UserService.class);

        mockUserService.createUser("Alice");

        // Verify method called with exact name "Alice"
        verify(mockUserService).createUser(eq("Alice"));
    }
}
OutputSuccess
Important Notes

Use any() when you don't care about the exact argument value.

Use eq() when you want to check for a specific value.

Mixing matchers and raw values in the same method call is not allowed; use matchers for all arguments.

Summary

Argument matchers help verify method calls flexibly.

any() matches any value of a type.

eq() matches an exact value.