Mockito BDDMockito then() Method Example

1. Introduction

BDDMockito is an interface of Mockito that provides a fluent API for BDD (Behavior-Driven Development) styled tests. The then() method is one of BDDMockito's offerings that allows for assertions on mocked methods. Unlike the traditional way of using verify(), BDDMockito provides a more readable syntax that aligns well with BDD's "Given, When, Then" structure. In this guide, we'll walk through an example of how to utilize the then() method from BDDMockito.

2. Example Steps

1. Define a simple service class that we wish to mock.

2. Set up a JUnit test class.

3. Mock the service class and define a behavior.

4. Invoke the method on the mocked object.

5. Use BDDMockito's then() to assert that the mocked method was called.

3. Mockito BDDMockito then() Method Example

// Step 1: Define a simple service class
class CalculatorService {
    int add(int a, int b) {
        return a + b;
    }
}

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

public class CalculatorServiceTest {

    @Test
    public void testAddMethod() {
        // Mock the CalculatorService class
        CalculatorService mockService = mock(CalculatorService.class);

        // Define behavior
        given(mockService.add(5, 3)).willReturn(8);

        // Step 4: Invoke the method on the mocked object
        int result = mockService.add(5, 3);
        assertEquals(8, result);

        // Step 5: Use BDDMockito's then() to assert
        then(mockService).should().add(5, 3);
    }
}

Output:

Test passed successfully. The add() method was called with arguments 5 and 3.

4. Step By Step Explanation

1. We began with a simple CalculatorService class that has an add() method.

2. In the CalculatorServiceTest, we created a mock of the CalculatorService.

3. We then used BDDMockito's given() to define a behavior, specifying that when the add() method of our mock object is called with arguments 5 and 3, it should return 8.

4. After invoking the add() method on our mock and getting the result, we made an assertion to ensure correctness.

5. Finally, using BDDMockito's then(), we made an assertion that the add() method on our mock object was called with the specified arguments. This provides a more readable way, especially in BDD styled tests, to verify that certain interactions took place.


Comments