简体   繁体   English

可以嘲弄一般异常

[英]Can mockito throw general Exception

Can Mockito throw the general Exception ? Mockito可以抛出一般Exception吗?

When I do, the test fails with 'org.mockito.exceptions.base.MockitoException: Checked Exception is invalid for this method' 当我这样做时,测试失败并显示“ org.mockito.exceptions.base.MockitoException:此方法的检查异常无效”

this is my @Test 这是我的@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);
}

You can raise a checked exception with a custom Answer implementation: 您可以使用自定义的Answer实现引发已检查的异常:

Mockito.doAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        throw new Exception();
    }
})
.when(service)
.getHTTPResponse("http://" + HOST + "/health");

The type argument Object may need to be changed to whatever the result of service.getHTTPResponse is. 类型参数Object可能需要更改为service.getHTTPResponse的结果。

As @ernest_k suggested, but with lambda function: 正如@ernest_k建议的那样,但具有lambda函数:

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

Mockito makes its best to ensure type safety and consistency in the passed argument, the returned type and the thrown exception. Mockito尽最大努力确保传递的参数,返回的类型和引发的异常中的类型安全性和一致性。
If Mockito "stops" you at compile time or at run time, in the very most of cases it is right and you don't have to try to bypass it but rather understand the issue root and correct it. 如果Mockito在编译时或运行时“停止”您,则在大多数情况下是正确的,您不必尝试绕过它,而是了解问题根源并进行更正。

In fact your actual requirement is an XY problem. 实际上,您的实际需求是XY问题。
In Java, a checked exception is checked. 在Java中,将检查已检查的异常。 It means that it has to be declared to be thrown by a method. 这意味着必须声明它由方法抛出。
If your getHTTPResponse() method doesn't declare throw Exception (or its parent class Throwable ) in its declaration, it means that the exception will never be thrown at runtime by invoking it and so your unit test makes no sense : you simulate a not possible scenario. 如果您的getHTTPResponse()方法未在其声明中声明throw Exception (或其父类Throwable ),则意味着永远不会通过调用它在运行时抛出该异常,因此您的单元测试毫无意义:您模拟一个not可能的情况。
I think that what you want is throwing RuntimeException in getHTTPResponse() such as : 我认为您想要在getHTTPResponse()抛出RuntimeException ,例如:

when(service.getHTTPResponse("http://" + HOST + "/health")).thenThrow(RuntimeException.class);

A RuntimeException doesn't need to be declared and that suits to your method declaration. 无需声明RuntimeException ,它适合您的方法声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM