mockito5.4.0单元测试(9) --调用同一个方法和参数依次返回不同的值thenReturn和thenThrow

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.

 

posted on 2023-06-25 10:20  梦幻朵颜  阅读(1255)  评论(0编辑  收藏  举报