简体   繁体   English

Mockito间谍对象,使用any()作为参数进行验证

[英]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. 我尝试使用ArgumentCaptor方法,但这也不起作用。

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. 这里的问题不是any()匹配器,事实上你调用put两次并试图验证一个调用。 Instead, you should use the times VerificationMode : 相反,您应该使用times VerificationMode

inOrder.verify(spyMap, times(2)).put(any(), any());
// Here ---------------^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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