Capturing multiple method arguments (using ArgumentCaptor) passed to a method in a consecutive call

This post explains how to capture multiple arguments passed to a method in a consecutive calls. Consider the below code

Class2


package package10;

public class Class2 {
    private int val;

    public void method2(int val) {
        this.val = val;
    }
}

Class1


package package10;

public class Class1 {
    private Class2 class2;

    public void method1(int val) {
        val = val * val;
        class2.method2(val);
    }
}

Class1Test


package package10;

import static org.mockito.Mockito.times;
import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class Class1Test {
    @InjectMocks
    private Class1 class1;

    @Mock
    private Class2 class2;

    @Test
    public void testMethod1() {
        ArgumentCaptor argument = ArgumentCaptor.forClass(Integer.class);
        
        class1.method1(3);
        class1.method1(4);
        class1.method1(5);
        
        Mockito.verify(class2, times(3)).method2(argument.capture());
        
        List values = argument.getAllValues();
        assertEquals(Long.valueOf(9), Long.valueOf(values.get(0)));
        assertEquals(Long.valueOf(16), Long.valueOf(values.get(1)));
        assertEquals(Long.valueOf(25), Long.valueOf(values.get(2)));
    }
}

Now we have to verify that expected arguments (twice of argument passed to Class1’s method1) are passed to Class2’s method2. Since the argument type is integer we will create an instance of ArgumentCaptor for Integer class as shown below
ArgumentCaptor argument = ArgumentCaptor.forClass(Integer.class);

Call the Class1’s method1 three times as shown below
class1.method1(3);
class1.method1(4);
class1.method1(5);

Now we verify whether Class2’s method2 is called three times using Verify method as shown below. In addition to verification, we pass ArgumentCaptor instance to capture the argument
Mockito.verify(class2, times(3)).method2(argument.capture());

Now we can get all the arguments passed to Class2’s method2 using the below method
List values = argument.getAllValues();

The list contains arguments values (passed to Class2’s method2) in the order of values passed to Class1’s method1.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s