Mockito – Verify Multiple Invocations with Different Arguments

Learn to write tests that invoke a method multiple times with different arguments – and then verify the method invocations and method arguments separately using the ArgumentCaptor.

1. Verify Multiple Invocations with ArgumentCaptor

The given unit test has mocked the HashMap class and invokes in put(key, value) code twice. It then verifies that the method had been invoked twice. The test further verifies all the different method arguments separately.

@RunWith(MockitoJUnitRunner.class)
public class MockitoExample 
{
  @Mock
  HashMap<String, Integer> hashMap;
 
  @Captor
  ArgumentCaptor<String> keyCaptor;
 
  @Captor
  ArgumentCaptor<Integer> valueCaptor;
 
  @Test
  public void saveTest() 
  {
    hashMap.put("A", 10);
    hashMap.put("B", 20);
     
    //1. Verify method was invoked N times
     
    Mockito.verify(hashMap, times(2)).put(keyCaptor.capture(), valueCaptor.capture());
 
    List<String> keys = keyCaptor.getAllValues();
    List<Integer> values = valueCaptor.getAllValues();
     
    //2. Verify method argument values as list
 
    assertEquals(Arrays.asList("A", "B"), keys);
    assertEquals(Arrays.asList(Integer.valueOf(10), Integer.valueOf(20)), values);
     
    //3. Verify method arguments separately
     
    assertEquals("A", keys.get(0));
    assertEquals("B", keys.get(1));
     
    assertEquals(Integer.valueOf(10), values.get(0));
    assertEquals(Integer.valueOf(20), values.get(1));
  }
}

2. Explanation

To capture and verify all the method arguments passed to a method when it is invoked multiple times, we shall follow the below steps:

  • Use Mockito.verify(mock, times(n)) to verify if the method was executed ‘n’ times.
  • Create as many ArgumentCaptor instances as the number of arguments in the method. In above example, we tested the HashMap which works on key-value pairs, so we created two ArgumentCaptor instances – one for key and second for value.
  • Use ArgumentCaptor.getAllValues() to retrieve all the values passed to one method parameter during all executions. It returns a List of passed argument values.
  • We can use assertEquals(expected, result) to verify that expected multiple arguments match with the retrieved values from ArgumentCaptor.

Happy Learning !!

Comments

Subscribe
Notify of
guest
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.