Issue
I am trying to test that my controller will indeed throw an error with the response code of 409 conflict. My controller looks like this:
if (Object != null) {
return Object;
} else {
throw new WebApplicationException(Response.Status.CONFLICT);
}
In the unit test I have something like this:
assertThrows(WebApplicationException.class, () -> controller.createObject();
Although I feel like this test isn't comprehensive enough as I haven't verified the response code of the call. How does one do that, if it is possible?
Solution
Instead of asserting that an exception is thrown, you need to enclose the code that should throw the exception within a try / catch, catch the exception, then get the response from the exception object and check its status code. Something like this:
try {
controller.createObject();
assertFail("should have thrown an exception");
} catch (WebApplicationClass ex) {
assertEquals(404, ex.getResponse().getStatusCode());
}
Answered By - Stephen C
Answer Checked By - Gilberto Lyons (JavaFixing Admin)