How do I test the catch statement below? My coverlay is failing and I am not sure how to cover this line.
public Method execute(@NonNull final String test) throws ServiceException {
try {
object = javaClient.fetchInfo(test);
} catch (ClientException | InternalServerError e) {
throw serviceExceptionAdapter.apply(e);
}
return object;
}
}
This is currently what I have in my test file:
private static final String test = "test";
private ExceptionAdapter serviceExceptionAdapter;
private JavaClient mockJavaClient;
private Proxy proxy;
@BeforeEach
void setup() {
this.serviceExceptionAdapter = mock(ExceptionAdapter.class);
this.mockJavaClient = mock(JavaClient.class);
proxy = new Proxy(mockJavaClient, serviceExceptionAdapter);
}
@Test
void test_InternalServerError() {
when(mockJavaClient.fetchInfo(any())).thenThrow(InternalServerError.class);
when(serviceExceptionAdapter.apply(any())).thenThrow(ServiceException.class);
assertThrows(ServiceException.class, () -> proxy.execute(test));
verify(serviceExceptionAdapter, times(1)).apply(any());
}
CodePudding user response:
I have to guess a little bit, as you didn't provide a full working example. From what I see in your catch block
} catch (ClientException | InternalServerError e) {
throw serviceExceptionAdapter.apply(e);
}
you expect the return value of your .apply(e)
function to be an exception and throw that exception. In your test however, your mocked serviceExceptionAdapter
doesn't return an Exception, but throws one instead:
when(serviceExceptionAdapter.apply(any()))
.thenThrow(ServiceException.class);
If my interpretations are correct, your code should work if you change the mentioned line in the test to the following:
when(serviceExceptionAdapter.apply(any()))
.thenReturn(new ServiceException(...));