BDDMockito willDoNothing() Method Example

1. Introduction

BDDMockito is Mockito's way of supporting Behavior-Driven Development (BDD) in unit tests. BDD encourages collaboration between developers, QA, and other stakeholders in a project, making the unit tests more readable and aligned with the business requirements. One of the methods provided by BDDMockito for mocking void methods is willDoNothing(). This method is particularly useful when we want to ignore the actual behavior of a void method in the mocked object. In this example, we'll demonstrate the use of willDoNothing().

2. Example Steps

1. Define a simple Service interface with a void method.

2. Set up a JUnit test class.

3. Use BDDMockito's willDoNothing() method to mock the behavior of the void method.

4. Run the test to ensure no side-effects are observed from the mocked void method.

3. BDDMockito willDoNothing() Method Example

// Step 1: Define a Service interface
interface Service {
    void performTask();
}

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

public class ServiceTest {

    @Test
    public void testPerformTask() {
        // Mock a Service using BDDMockito
        Service mockService = mock(Service.class);

        // Step 3: Use BDDMockito's willDoNothing() method
        willDoNothing().given(mockService).performTask();

        // Invoke the mocked method
        mockService.performTask();

        // Since the method is void, we rely on no exceptions or side-effects as verification
    }
}

Output:

Test passed successfully without any exceptions or unexpected side-effects.

4. Step By Step Explanation

1. We started by defining a Service interface that has a performTask() method, which is a void method.

2. In the ServiceTest class, we created a mock of the Service.

3. With the help of BDDMockito's willDoNothing() method, we ensured that when performTask() on the mock object is invoked, it does nothing.

4. Finally, the test invokes the performTask() method. Since it's a void method, the successful completion of the test (without exceptions or side-effects) acts as our verification.


Comments