java - 在 Mockito 中 stub 默认值

标签 java mockito stubbing

我怎样才能 stub 一个方法,以便在给定一个我不期望的值时,它返回一个默认值?

例如:

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

在上面的示例中,最后一个 stub 优先,因此映射将始终返回默认值。

最佳答案

我找到的最佳解决方案是颠倒 stub 的顺序:

Map<String, String> map = mock(Map.class);
when(map.get(anyString())).thenReturn("I don't know that string");
when(map.get("abcd")).thenReturn("defg");
when(map.get("defg")).thenReturn("ghij");

当默认抛出异常时,你可以只使用 doThrow 和 doReturn

doThrow(new RuntimeException()).when(map).get(anyString());
doReturn("defg").when(map).get("abcd");
doReturn("ghij").when(map).get("defg");

https://static.javadoc.io/org.mockito/mockito-core/2.18.3/org/mockito/Mockito.html#12

关于java - 在 Mockito 中 stub 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4216366/

相关文章:

java - Eclipse for Java (EE) Developers 和 Eclipse Classic 有什么区别?

scala - Mockito 在 ScalaTest 中的回答

java - Mockito 验证 void 方法内的方法调用

javascript - 如何(sinon) stub 外部模块函数?

coffeescript - 用于 window.location.search 的 Sinon.JS stub

ruby-on-rails - RSpec stub 不包含多个嵌套的Describe block

java - String.split,将 String 转换为 int

java - 使 @Transactional 和 @Rollback 与 Spring Boot Test 一起使用

java - Spring session ,部署后从 "local class incompatible"恢复

java - 使用 Mockito 测试方法调用