mockito 可以抛出一般异常

Den*_*din 2 java exception mockito

Mockito 可以扔将军Exception吗?

当我这样做时,测试失败并显示“org.mockito.exceptions.base.MockitoException: Checked Exception is invalid for this method”

这是我的 @Test

public void testServiceSomeError() throws ClientProtocolException, IOException {
    //Arrange    
    HealthService service = Mockito.mock(HealthService.class);

    when(service.executeX(HOST)).thenCallRealMethod();
    when(service.getHTTPResponse("http://" + HOST + "/health")).thenThrow(Exception.class);
    //Act
    String actual = service.executeX(HOST);

    //Assert
    assertEquals(ERROR, actual);
}
Run Code Online (Sandbox Code Playgroud)

小智 5

正如@ernest_k 所建议的那样,但使​​用 lambda 函数:

Mockito.doAnswer(i -> { throw new Exception(); })
    .when(service)
    .getHTTPResponse("http://" + HOST + "/health");
Run Code Online (Sandbox Code Playgroud)