Mockito BDDMockito willReturn() Method Example

1. Introduction

Behavior-Driven Development (BDD) is a testing methodology that focuses on the behavior of software units. BDDMockito is Mockito's approach to BDD. The willReturn() method of BDDMockito allows testers to set up mock objects to return specific values, making it easier to control the behavior of mocks in tests. This tutorial will demonstrate the use of the willReturn() method.

2. Example Steps

1. Create an interface representing a basic calculator with a method to add two numbers.

2. Set up a JUnit test class.

3. Use BDDMockito's willReturn() method to make the mock calculator return a specified value.

4. Run the test to verify the behavior of the mock.

3. Mockito BDDMockito willReturn() Method Example

// Step 1: Define a calculator interface
interface Calculator {
    int add(int a, int 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.assertEquals;

public class CalculatorTest {

    @Test
    public void testAdd() {
        // Create a mock of Calculator using BDDMockito
        Calculator mockCalculator = mock(Calculator.class);

        // Step 3: Use BDDMockito's willReturn() method
        given(mockCalculator.add(5, 3)).willReturn(8);

        // Assert that the mock's add method returns the expected value
        int result = mockCalculator.add(5, 3);
        assertEquals(8, result);
    }
}

Output:

Test passed successfully with no errors.

4. Step By Step Explanation

1. We defined a simple Calculator interface with an add() method that takes two integers and returns their sum.

2. In the CalculatorTest class, we created a mock instance of the Calculator.

3. With the help of BDDMockito's willReturn() method, we set up the mock to return 8 when its add(5, 3) method is called.

4. Finally, we used JUnit's assertEquals() method to verify that the mock's add() method behaves as expected, confirming that it returns the value we've set up with willReturn().


Comments