我怎样才能 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/