How to run a JUnit Test case on Checked Exception. For e.g. HttpClient execute method shows checked IOException but i am not sure what to assert/expect.
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
@Test
public void throwIOExceptionOnHttpRequest() {
HttpClient httpClient = mock(HttpClient.class)
HttpUriRequest httpUriRequest = mock(HttpUriRequest.class);
try{
when(httpClient.execute(any(HttpPost.class))).thenThrow(IOException.class);
httpClient.execute(httpUriRequest);
//Ideally nothing should work after this as exception is thrown
//fail("This will fail") // this statement will throw Assertion Error
}
catch (IOException io) {
}
}
If i try using expected method, this returns IOException never thrown.
Exception thrown =
assertThrows(
IOException.class,
() -> {
when(httpClient.execute(any(HttpPost.class))).thenThrow(IOException.class);
});
Truth.assertThat(thrown).hasMessageThat().contains("IOException");
}