Mockito BDDMockito willAnswer() Method Example

1. Introduction

Behavior-Driven Development (BDD) is an approach to software development that encourages collaboration between developers, QA, and non-technical or business participants in a software project. BDDMockito is Mockito's implementation to support BDD-style verification of mock behavior. The willAnswer() method from BDDMockito allows us to provide a dynamic response based on the input arguments of the called method. In this tutorial, we will demonstrate how to use the willAnswer() method.

2. Example Steps

1. Create an interface representing a list manager with methods to add and retrieve items.

2. Set up a JUnit test class.

3. Use BDDMockito's willAnswer() method to dynamically mock the behavior of the addItem() method.

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

3. Mockito BDDMockito willAnswer() Method Example

// Step 1: Define a ListManager interface
interface ListManager {
    void addItem(String item);
    String getItem(int index);

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

public class ListManagerTest {

    public void testAddItem() {
        // Mock a ListManager using BDDMockito
        ListManager mockListManager = mock(ListManager.class);

        // Create a real list to simulate the behavior
        List<String> list = new ArrayList<>();

        // Step 3: Use BDDMockito's willAnswer() method
        willAnswer(invocation -> {
            String item = invocation.getArgument(0);
            return null;


        // Add an item to the mock list manager

        // Assert that the mock's getItem method returns the expected value
        String result = mockListManager.getItem(0);
        assertEquals("apple", result);


Test passed successfully with no errors.

4. Step By Step Explanation

1. We first defined a ListManager interface that represents a basic list with methods to add and retrieve items.

2. In the ListManagerTest class, we mocked an instance of the ListManager.

3. Using BDDMockito's willAnswer() method, we dynamically mocked the behavior of the addItem() method to add items to a real list.

4. Then, we added an item to the mock list manager and verified with JUnit's assertEquals() method that the getItem() method of the mock returns the correct item.