Mockito BDDMockito Example

1. Introduction

Behavior-Driven Development (BDD) is an agile software development approach that encourages collaboration among developers, QA, and non-technical participants in a software project. Mockito offers BDDMockito which is a BDD-style variant of its typical mocking API. This API is more in line with the "Given, When, Then" style of writing specifications in BDD.

2. Example Steps

1. Define a sample service to be tested.

2. Use the BDDMockito API to write BDD-style tests for the service.

3. Demonstrate the usage of given(), willThrow(), and willReturn() methods from BDDMockito.

4. Run the tests and observe the output.

3. Mockito BDDMockito Example

// Step 1: Define a sample service
class SampleService {
    String processData(String input) {
        return "Processed: " + input;
    }
}

// Step 2: Use the BDDMockito API to write BDD-style tests
import org.junit.jupiter.api.Test;
import static org.mockito.BDDMockito.*;

public class SampleServiceTest {

    @Test
    public void testProcessData() {
        // Mock the SampleService using BDDMockito
        SampleService mockService = mock(SampleService.class);

        // Given: Set up the mock behavior
        given(mockService.processData("rawData")).willReturn("Mocked: rawData");

        // When: Call the method
        String result = mockService.processData("rawData");

        // Then: Assert and print the result
        System.out.println(result);

        // Given: Set up the mock to throw an exception
        given(mockService.processData("exceptionData")).willThrow(new RuntimeException("Exception occurred"));

        // When: Calling the method which throws an exception
        try {
            mockService.processData("exceptionData");
        } catch (RuntimeException ex) {
            // Then: Print the exception
            System.out.println(ex.getMessage());
        }
    }
}

Output:

Mocked: rawData
Exception occurred

4. Step By Step Explanation

1. We have a simple SampleService with a processData method that appends "Processed:" to the provided input.

2. In SampleServiceTest, using BDDMockito, we mock the SampleService.

3. The given() method is BDDMockito's replacement for Mockito's when(). We use it to specify a condition, i.e., when processData("rawData") is called on the mock, then it should return "Mocked: rawData".

4. We demonstrate the usage of willReturn() to stub the desired method return value.

5. Another demonstration is done using willThrow() where we specify that calling processData("exceptionData") should throw a RuntimeException.

6. The results align with our mock setup, showcasing the power and elegance of BDDMockito in writing BDD-style tests.


Comments