Mockito BDDMockito.any() Method Example

1. Introduction

In Mockito's BDD (Behavior-Driven Development) style API, BDDMockito, the any() method is used to match any argument of a given type, regardless of its value. This is particularly useful when you want to stub or verify method calls without being specific about the argument values. In this post, we'll demonstrate how to use the any() method in BDDMockito to make our mock expectations more flexible.

2. Example Steps

1. Create a sample service class with methods we want to mock.

2. Setup a JUnit test class.

3. Mock the service class.

4. Define a behavior for a method using the any() method to match any argument.

5. Invoke the method on the mocked object.

6. Use BDDMockito's then() to assert the interactions.

3. Mockito BDDMockito.any() Method Example

// Step 1: Create a sample service class
class NotificationService {
    String sendNotification(String message) {
        return "Notification sent: " + message;
    }
}

// Step 2: Setup a JUnit test class
import org.junit.jupiter.api.Test;
import static org.mockito.BDDMockito.*;
import static org.junit.jupiter.api.Assertions.*;

public class NotificationServiceTest {

    @Test
    public void testSendNotification() {
        // Step 3: Mock the NotificationService class
        NotificationService mockService = mock(NotificationService.class);

        // Step 4: Define behavior using any()
        given(mockService.sendNotification(any(String.class))).willReturn("Notification mocked!");

        // Step 5: Invoke the method on the mocked object with different messages
        String result1 = mockService.sendNotification("Hello");
        String result2 = mockService.sendNotification("World");

        assertEquals("Notification mocked!", result1);
        assertEquals("Notification mocked!", result2);

        // Step 6: Use BDDMockito's then() to assert
        then(mockService).should(times(2)).sendNotification(any(String.class));
    }
}

Output:

Test passed successfully. The sendNotification() method was called twice with any string as its argument.

4. Step By Step Explanation

1. We started with a basic NotificationService class with a method sendNotification().

2. In our test class NotificationServiceTest, we mocked NotificationService.

3. Using BDDMockito's given(), we defined a behavior for our mock object where the sendNotification() method will return "Notification mocked!" regardless of its argument, thanks to any(String.class).

4. We invoked the sendNotification() method on our mock with two different messages.

5. Using JUnit assertions, we ensured that our mock returned the expected value both times.

6. Finally, with BDDMockito's then(), we asserted that the sendNotification() method on our mock object was called twice with any string as its argument.


Comments