- 无返回值方法的异常mock
doThrow(new RuntimeException()).when(testMethod).testMethod(anyString());
Assertions.assertThrows(Exception.class, () -> testMethod.testMethod("foo"));
- 有返回值的普通mock
given(testMethod.testMethodWithReturn(anyString())).willThrow(new Exception("TestError"));
或者
when(testMethod.testMethodWithReturn(anyString())).thenThrow(new Exception("TestError"));
- 根据特定入参抛出异常(answer方法)
when(testMethod.testMethodWithReturn(anyString())).thenAnswer(
new Answer() {
public Object answer(InvocationOnMock invocation) throws Exception {
Object[] args = invocation.getArguments();
if (args[0].equals("foo")) {
throw new Exception("mock 异常应答");
}
return "ok";
}
});
本文介绍了如何使用Mockito库在单元测试中对无返回值和有返回值的方法进行异常模拟。对于无返回值的方法,可以使用doThrow().when()来抛出预期的异常;而对于有返回值的方法,可以通过given()或when().thenThrow()来实现异常模拟。此外,还展示了如何根据特定输入参数定制异常回答,使得在满足特定条件时抛出异常。

8206

被折叠的 条评论
为什么被折叠?



