asfsfsdfdsfdsf
asfsfsdfdsfdsf

Reputation: 81

How do I verify the HTTP status code if it is a subclass of WebApplicationException?

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?

Upvotes: 0

Views: 4190

Answers (2)

Catmmao
Catmmao

Reputation: 11

assetThrow method description

Assert that execution of the supplied executable throws an exception of the expectedType and return the exception. If no exception is thrown, or if an exception of a different type is thrown, this method will fail. If you do not want to perform additional checks on the exception instance, simply ignore the return value.

the return value of the assertThrows method is your exception instance, so you can do this

WebApplicationClass e = assertThrows(HttpException.class, () -> controller.createObject());

// perform additional checks
assertEquals(xxx, e.getResponse().getxxx);

Upvotes: 1

Stephen C
Stephen C

Reputation: 718946

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

Upvotes: 2

Related Questions