Dendin
Dendin

Reputation: 173

Can mockito throw general Exception

Can Mockito throw the general Exception?

When I do, the test fails with 'org.mockito.exceptions.base.MockitoException: Checked Exception is invalid for this method'

this is my @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);
}

Upvotes: 2

Views: 3542

Answers (3)

davidxxx
davidxxx

Reputation: 131496

Mockito makes its best to ensure type safety and consistency in the passed argument, the returned type and the thrown exception.
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.

In fact your actual requirement is an XY problem.
In Java, a checked exception is checked. 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.
I think that what you want is throwing RuntimeException in getHTTPResponse() such as :

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

A RuntimeException doesn't need to be declared and that suits to your method declaration.

Upvotes: 1

Ed Brook
Ed Brook

Reputation: 328

As @ernest_k suggested, but with lambda function:

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

Upvotes: 7

ernest_k
ernest_k

Reputation: 45339

You can raise a checked exception with a custom Answer implementation:

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.

Upvotes: 2

Related Questions