Mockito 中的存根默认值
如何存根一个方法,以便在给定一个我不期望的值时,它返回一个默认值?
例如:
Map<String, String> map = mock(Map.class);
when(map.get("abcd")).thenReturn("defg");
when(map.get("defg")).thenReturn("ghij");
when(map.get(anyString())).thenReturn("I don't know that string");
第 2 部分:如上所述,但抛出异常:
Map<String, String> map = mock(Map.class);
when(map.get("abcd")).thenReturn("defg");
when(map.get("defg")).thenReturn("ghij");
when(map.get(anyString())).thenThrow(new IllegalArgumentException("I don't know that string"));
在上面的示例中,最后一个存根优先,因此映射将始终返回默认值。
How can I stub a method such that when given a value I'm not expecting, it returns a default value?
For example:
Map<String, String> map = mock(Map.class);
when(map.get("abcd")).thenReturn("defg");
when(map.get("defg")).thenReturn("ghij");
when(map.get(anyString())).thenReturn("I don't know that string");
Part 2: As above but throws an exception:
Map<String, String> map = mock(Map.class);
when(map.get("abcd")).thenReturn("defg");
when(map.get("defg")).thenReturn("ghij");
when(map.get(anyString())).thenThrow(new IllegalArgumentException("I don't know that string"));
In the above examples, the last stub takes precedence so the map will always return the default.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现的最好的解决方案是反转存根的顺序:
当默认抛出异常时,您可以只使用 doThrow 和 doReturn
https://static.javadoc.io/org.mockito/mockito-core/2.18.3/org/mockito/Mockito .html#12
The best solution I have found is to reverse the order of the stubs:
When the default is to throw an exception you can just use doThrow and doReturn
https://static.javadoc.io/org.mockito/mockito-core/2.18.3/org/mockito/Mockito.html#12
这是一种迂回的方式来做到这一点。但它应该有效。
It's kind of a roundabout way to do this. But it should work.
您可以使用:
You can use: