Mockito.doAnswer() Example

1. Introduction

Mockito provides a versatile way to handle method invocations with its doAnswer() method. With doAnswer(), you can define custom behavior for a mocked method, allowing more flexibility compared to simple stubbing. This comes in handy when you need to perform specific actions upon a method call or when the method's behavior depends on its arguments.

2. Example Steps

1. Create a simple service interface with a method that modifies an argument.

2. Mock this service using Mockito in a test class.

3. Use the doAnswer() method to specify custom behavior for the mocked method.

4. Invoke the method and observe the behavior.

3. Mockito.doAnswer() Example

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.List;

// Step 1: Create a simple service interface
interface ItemService {
    void addItemToList(List<String> items, String item);
}

public class ItemServiceTest {

    @Test
    public void testDoAnswerWithMockito() {
        // Step 2: Mock the ItemService
        ItemService mockedItemService = mock(ItemService.class);

        // Step 3: Use doAnswer() to specify custom behavior
        doAnswer(invocation -> {
            List<String> items = invocation.getArgument(0);
            String item = invocation.getArgument(1);
            items.add(item + " - modified by doAnswer");
            return null; // return is needed as the method's return type is void
        }).when(mockedItemService).addItemToList(anyList(), anyString());

        // Create a sample list
        List<String> sampleItems = new ArrayList<>();

        // Step 4: Invoke the method
        mockedItemService.addItemToList(sampleItems, "TestItem");

        // Print the modified list
        System.out.println(sampleItems);
    }
}

Output:

[TestItem - modified by doAnswer]

4. Step By Step Explanation

1. We begin by defining an ItemService interface with a method named addItemToList. This method is designed to add an item to a list.

2. In the ItemServiceTest class, we mock the ItemService.

3. The core part is setting up the behavior with doAnswer(). We fetch the method's arguments from the invocation and modify the item before adding it to the list.

4. After setting up the mock, we create a sample list and invoke the addItemToList method using the mock. As defined in the doAnswer(), the item gets modified before being added.

5. The output demonstrates the ability of doAnswer() to provide custom behavior, proving its utility when more intricate mocking is required.


Comments