mockito官方文档地址:https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#exact_verification
// mock一个对象
List singleMock = mock(List.class);
when(singleMock.get(20))
.thenThrow(new RuntimeException()) // mock第一次调用时抛出异常
.thenReturn("foo20"); // 设定第二次调用时,返回正常值:foo20
try {
//第一次调用: throws runtime exception:
singleMock.get(20);
} catch (Exception e) {
log.error("打印预期错误RuntimeException");
}
//第二次调用: 打印 "foo20"
System.out.println(singleMock.get(20));
//任何连续呼叫:Any consecutive call: prints "foo20" as well (last stubbing wins).
System.out.println(singleMock.get(20));
// mock第二个对象
List secondMock = mock(List.class);
when(secondMock.get(50))
.thenReturn("one", "two", "three");
log.info("secondMock第一次调用:{}", secondMock.get(50)); // secondMock第一次调用:one
log.info("secondMock第二次调用:{}", secondMock.get(50)); // secondMock第二次调用:two
log.info("secondMock第三次调用:{}", secondMock.get(50)); // secondMock第三次调用:three
end.
标签:调用,secondMock,get,--,mockito5.4,mockito,单元测试,singleMock,mock From: https://www.cnblogs.com/zhuwenjoyce/p/17502291.html