- 无返回值方法的异常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";
}
});