How to capture arguments of a method called multiple times using Mockito

December 01, 2020 No comments Mockito Java Mock captor

1. Introduction

In this article, we will present how to capture all arguments used in multiple method calls using the Mockito testing framework.

2. Using @Captor annotation

Mockito provides a special @Captor functionality used to capture the arguments passed to a method in mock object. This annotation always goes hand in hand with ArgumentCaptor.

Let's check a simple unit test that uses @Captor and ArgumentCaptor:

package com.frontbackend.libraries.mockito;

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import lombok.AllArgsConstructor;
import lombok.Getter;

@RunWith(MockitoJUnitRunner.class)
public class MockitoCaptorAllValues {

    @AllArgsConstructor
    static class Person {
        @Getter
        private final String name;
    }

    @Mock
    private List<Person> list;

    @Captor
    private ArgumentCaptor<Person> personArgumentCaptor;

    @Test
    public void shouldCaptureListParameters() {
        list.add(new Person("John"));
        list.add(new Person("Alan"));

        verify(list, times(2)).add(personArgumentCaptor.capture());

        List<Person> allValues = personArgumentCaptor.getAllValues();

        Assert.assertEquals("John", allValues.get(0)
                                             .getName());
        Assert.assertEquals("Alan", allValues.get(1)
                                             .getName());
    }
}

In this example, we create a mock object with a list of Person objects. Then we add two persons to the list and using getAllValues() we get arguments from all method invocations.

This test answering the question given in the article title: to capture all arguments we used the argumentCaptor.getAllValues() method.

3. Conclusion

In this short article, we presented how to capture all arguments of a method that was called multiple times. Luckily Mockito holds all information about method invocations for future assertions.

As usual the code used in this article is available under GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}