mockito官方文档地址: https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#do_family_methods_stubs
// mock一个对象
HashMap mockMap = mock(HashMap.class);
doCallRealMethod方法示例:
// 当mock对象调用put和size方法时,都调用真实的方法
doCallRealMethod().when(mockMap).put(anyString(), any());
doCallRealMethod().when(mockMap).size();
mockMap.put("key1", "value1");
mockMap.put("key2", "value2");
log.info("print0: size = {}", mockMap.size());
doThrow方法示例:
try {
doThrow(new RuntimeException()).when(mockMap).get("0");
log.info("print1: {}", mockMap.get("0"));
} catch (Exception e) {
log.error("doThrow...when mockMap.get(\"0\")");
}
doReturn方法示例:
doReturn("aaa-value").when(mockMap).get("aaa");
log.info("print1: {}", mockMap.get("aaa"));
doAnswer方法示例:
doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Object mock = invocation.getMock();
return "自定义返回值: " + Arrays.toString(args); // 可以自定义返回值
}
}).when(mockMap).get("bbb");
log.info("print2: {}", mockMap.get("bbb")); // 自定义返回值: bbb
doNothing方法示例:
doCallRealMethod().when(mockMap).put(anyString(), any());
doCallRealMethod().when(mockMap).size();
mockMap.put("key1", "value1");
mockMap.put("key2", "value2");
doNothing().when(mockMap).clear(); // 如果调用clear,则什么都不做
mockMap.clear(); // 这里什么都不做
log.info("print3: size = {}", mockMap.size()); // 因为clear什么都没做,所以这里打印的是size=2
try {
doNothing(). // 第一次调用clear什么都不做
doThrow(new RuntimeException()) // 第二次调用clear的时候报错
.when(mockMap).clear();
mockMap.clear();// 第一次调用clear什么都不做
log.info("print4: mockMap.clear()");
mockMap.clear();// 第二次调用clear的时候报错\
log.info("print5: 这一条日志应该打印不出来了");
} catch (Exception e) {
log.error("doThrow...when mockMap.clear()");
}
end.
标签:11,do,donnothing,log,get,clear,when,mockMap,size From: https://www.cnblogs.com/zhuwenjoyce/p/17506089.html