4

I have a simple unit test

Map<String, String> spyMap = spy(Map.class); 
spyMap.put("a", "A");
spyMap.put("b", "B");

InOrder inOrder = inOrder(spyMap);

inOrder.verify(spyMap).put(any(), any());
inOrder.verify(spyMap).put(any(), any());

But this throws an error. The following works:

inOrder.verify(spyMap).put("a", "A");
inOrder.verify(spyMap).put("b", "B");

So I can only test with exact string matches? That seems limiting to me. My test method actually generates a random String, so I do not know what exactly will be inserted into the map. I tried using ArgumentCaptor methods, but that did not work either.

Map<String, String> spyMap = spy(Map.class); 
spyMap.put("a", "A");
spyMap.put("b", "B");

ArgumentCaptor<String> arg1 = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> arg2 = ArgumentCaptor.forClass(String.class);

verify(spyMap).put(arg1.capture(), arg2.capture());
Mureinik
  • 297,002
  • 52
  • 306
  • 350
user2689782
  • 747
  • 14
  • 31

1 Answers1

6

The issue here isn't the any() matcher, it's the fact that you call put twice and are trying to verify a single call. Instead, you should use the times VerificationMode:

inOrder.verify(spyMap, times(2)).put(any(), any());
// Here ---------------^
Mureinik
  • 297,002
  • 52
  • 306
  • 350