简体   繁体   中英

How to unit test the catch exception statement?

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:

@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());
}

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(...));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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