简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM