Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

junit test on ContainerRequestFilter - validate WebApplicationException's entity

Tags:

junit

jersey

I have build a little authentication filter based on jersey's ContainerRequestFilter.

This throws a few WebAplicationExceptions when the request is unauthorized, and i want to test this.

I already have this, to check that an exception is raised when the filter method is invoked and the request is unauthorized:

@Category(CommitTest.class)
public class BasicAuthenticationFilterTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void someInvalidAuthTest() throws IOException {
        //...setup auth filter, and mock objects
        //Expect an WebApplicationException

        thrown.expect(WebApplicationException.class);
        authenticationFilter.filter(mockRequestContext);
    }
}

I can do this just fine, and my test runs fine. But i would like to be able to validate the response of the exception.

edit

To clarify, i normally throw my exceptions like this:

ApiError error = new ApiError(1, "UNAUTHORIZED", "No or empty authorization header");
throw new WebApplicationException(
    error.getMessage(),
    Response.status(Response.Status.UNAUTHORIZED).entity(error).build());

I want to validate both the response and entity thrown in the exception. Now i know this might not even be possible. But i had to ask to make sure.

Or should i do this testing a completely other way, and actually set up an in-memory type "server" that uses my auth-filter, and make an actual request to it (and then validate the response?)

like image 362
Martin Hansen Avatar asked Jan 01 '26 02:01

Martin Hansen


1 Answers

You can update your rule to check the exception message, but to get at the response entity it would probably be easier to try/catch like this:

@Category(CommitTest.class)
public class BasicAuthenticationFilterTest {

    @Test
    public void someInvalidAuthTest() throws IOException {
        //...setup auth filter, and mock objects

        try {
            authenticationFilter.filter(mockRequestContext);
            fail("expect a WebApplicationException");
        }
        catch (WebApplicationException e) {
            Response r = e.getResponse();

            // validate status code
            assertEquals(Response.Status.UNAUTHORIZED, r.getStatusInfo());

            // validate entity
            ApiError error = r.readEntity(ApiError.class);
            assertEquals("No or empty authorization header", error.getMessage());
        }
    }
}
like image 131
Alden Avatar answered Jan 05 '26 05:01

Alden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!