Mockito ArgumentMatchers Example

1. Introduction

Mockito's ArgumentMatchers provides a way to specify flexible arguments in stubbing and verification. Instead of hardcoding specific argument values, ArgumentMatchers allows you to specify general conditions or characteristics of the arguments. This feature is especially helpful when you're not concerned about the exact value of an argument but rather its type, nullity, or some other general characteristic.

2. Example Steps

1. Create a simple service that has a method accepting arguments.

2. Mock this service in a test class.

3. Use Mockito's ArgumentMatchers to stub the method's behavior based on general argument conditions.

4. Verify the method's behavior using the same ArgumentMatchers.

3. Mockito ArgumentMatchers Example

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

public class NotificationService {
    public String sendNotification(String message, int userId) {
        // Logic to send notification
        return "Notification sent!";
    }
}

public class NotificationServiceTest {

    @Test
    public void testSendNotificationWithArgumentMatchers() {
        // Mock the NotificationService
        NotificationService mockedNotificationService = mock(NotificationService.class);

        // Stubbing the sendNotification method using ArgumentMatchers
        when(mockedNotificationService.sendNotification(anyString(), anyInt())).thenReturn("Mocked response!");

        // Calling the method on the mock
        String response = mockedNotificationService.sendNotification("Hello", 123);

        // Verifying the method's behavior with ArgumentMatchers
        verify(mockedNotificationService).sendNotification(anyString(), eq(123));

        System.out.println("Response: " + response);
    }
}

Output:

Response: Mocked response!

4. Step By Step Explanation

1. We started with a simple NotificationService class that has a method named sendNotification. This method takes a message (String) and a userId (int) as its parameters.

2. In the NotificationServiceTest class, we mocked the NotificationService.

3. Using Mockito's anyString() and anyInt() ArgumentMatchers, we stubbed the behavior of the sendNotification method. This means that regardless of the specific String or int value passed to the method, it will always return "Mocked response!" when invoked on the mock object.

4. We then called the sendNotification method on the mock object and printed the response.

5. Finally, using the verify() method, we confirmed that the method was indeed called with any String and the exact integer value 123.

6. The output "Response: Mocked response!" confirms that the stubbing using ArgumentMatchers was successful.


Comments