Mockito: Verifying method arguments with inOrder


Posted by Steven

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):

  1. @Test
  2. void capturingArgumentOfMultipleSubsequentCalls() {
  3.  
  4. MyClass myClassSpy = spy(new MyClass());
  5.  
  6. myClassSpy.receivingAnArgument(1);
  7. myClassSpy.receivingAnArgument(2);
  8. myClassSpy.receivingAnArgument(3);
  9.  
  10. InOrder inOrder = inOrder(myClassSpy);
  11. inOrder.verify(myClassSpy).receivingAnArgument(argThat((i) -> (i == 1)));
  12. inOrder.verify(myClassSpy).subsequentlyCalledMethod(argThat((i) -> (i == 1)));
  13. inOrder.verify(myClassSpy).receivingAnArgument(argThat((i) -> (i == 2)));
  14. inOrder.verify(myClassSpy).subsequentlyCalledMethod(argThat((i) -> (i == 2)));
  15. inOrder.verify(myClassSpy).receivingAnArgument(argThat((i) -> (i == 3)));
  16. inOrder.verify(myClassSpy).subsequentlyCalledMethod(argThat((i) -> (i == 3)));
  17.  
  18. }
  19.  
  20. class MyClass {
  21.  
  22. void receivingAnArgument(Integer i) {
  23. System.out.println("Received a " + i);
  24. subsequentlyCalledMethod(i);
  25. }
  26.  
  27. void subsequentlyCalledMethod(Integer i) {
  28. System.out.println("Private method called with " + i);
  29. }
  30. }
Share: