Yesterday, I learned how to verify the method parameter for multiple method calls in Mockito. My pair-programmer and I wrote code that send multiple messages to an Amazon SQSClient. We wanted to test if a) all expected send-calls were executed and b) if all of those had the correct argument.
On SO, we found the solution (rewritten for better understanding):
@Test
void capturingArgumentOfMultipleSubsequentCalls() {
MyClass myClassSpy = spy(new MyClass());
myClassSpy.receivingAnArgument(1);
myClassSpy.receivingAnArgument(2);
myClassSpy.receivingAnArgument(3);
InOrder inOrder = inOrder(myClassSpy);
inOrder.verify(myClassSpy).receivingAnArgument(argThat((i) -> (i == 1)));
inOrder.verify(myClassSpy).subsequentlyCalledMethod(argThat((i) -> (i == 1)));
inOrder.verify(myClassSpy).receivingAnArgument(argThat((i) -> (i == 2)));
inOrder.verify(myClassSpy).subsequentlyCalledMethod(argThat((i) -> (i == 2)));
inOrder.verify(myClassSpy).receivingAnArgument(argThat((i) -> (i == 3)));
inOrder.verify(myClassSpy).subsequentlyCalledMethod(argThat((i) -> (i == 3)));
}
class MyClass {
void receivingAnArgument(Integer i) {
System.out.println("Received a " + i);
subsequentlyCalledMethod(i);
}
void subsequentlyCalledMethod(Integer i) {
System.out.println("Private method called with " + i);
}
}