user2689782
user2689782

Reputation: 757

Mockito spy object, verify with any() as argument

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());

Upvotes: 4

Views: 6503

Answers (1)

Mureinik
Mureinik

Reputation: 311528

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 ---------------^

Upvotes: 6

Related Questions