Mockito BDDMockito.times() Method Example

1. Introduction

In the BDD (Behavior-Driven Development) style API provided by Mockito, known as BDDMockito, the times() method is utilized to specify the number of times a method is expected to be called. It aids in verifying the interactions with the mocked object more precisely. This post will illustrate the usage of the times() method in BDDMockito to assert our mock interactions accurately.

2. Example Steps

1. Define a sample service class with methods that we'll mock.

2. Set up a JUnit test class.

3. Mock the service class.

4. Define behaviors for the mocked methods.

5. Invoke the methods on the mocked object.

6. Use BDDMockito's then() along with times() to verify the interactions.

3. Mockito BDDMockito.times() Method Example

// Step 1: Define a sample service class
class OrderService {
    void processOrder(String order) {
        // logic to process the order
    }
}

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

public class OrderServiceTest {

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

        // Step 4: Define behavior (in this example, we don't define any return behavior since the method is void)

        // Step 5: Invoke the method on the mocked object multiple times
        mockService.processOrder("Order1");
        mockService.processOrder("Order2");
        mockService.processOrder("Order3");

        // Step 6: Use BDDMockito's then() along with times() to verify interactions
        then(mockService).should(times(3)).processOrder(anyString());
    }
}

Output:

Test passed successfully. The processOrder() method on the mocked object was verified to be called three times.

4. Step By Step Explanation

1. We initiated with a simple OrderService class with a method named processOrder().

2. Inside our OrderServiceTest test class, we created a mock for OrderService.

3. For this example, since the processOrder() method is void, we did not define any specific return behavior for our mock.

4. We called the processOrder() method on our mock object thrice with different order strings.

5. At the end, we employed BDDMockito's then() and the times() method to verify that the processOrder() method on our mock object was indeed invoked three times with any string as its argument.


Comments