mockito5.4.0单元测试(10) --通过thenAnswer方法自定义callback返回值
mockito官方文档地址: https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#exact_verification
// mock一个对象
HashMap mockMap = mock(HashMap.class);
mockMap.put("key1", "value1");
mockMap.put("key2", "value2");
when(mockMap.get(anyString())).thenAnswer(
new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Object mock = invocation.getMock();
return "called with arguments: " + Arrays.toString(args); // 可以自定义返回值
}
});
//Following prints "called with arguments: [foo]"
System.out.println(mockMap.get("key1")); // 返回值自定义为: called with arguments: [key1]
System.out.println(mockMap.get("key2")); // 返回值自定义为: called with arguments: [key2]
System.out.println(mockMap.get("key3")); // 返回值自定义为: called with arguments: [key3]
end.
![](https://images.cnblogs.com/cnblogs_com/zhuwenjoyce/945554/o_201113020411my-zhifubao-shouqianma.jpeg)