Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test jersey2 request filters?

In my jersey-2 application I'm using a very simple ContainerRequestFilter that will check for basic authentication (probably reinventing the wheel, but bear with me). Filter goes somewhat like this

@Override
public void filter(ContainerRequestContext context) throws IOException {
    String authHeader = context.getHeaderString(HttpHeaders.AUTHORIZATION);
    if (StringUtils.isBlank(authHeader)) {
        log.info("Auth header is missing.");
        context.abortWith(Response.status(Response.Status.UNAUTHORIZED)
                .type(MediaType.APPLICATION_JSON)
                .entity(ErrorResponse.authenticationRequired())
                .build());
    }
}

Now I'd like to write a test for it, mocking the ContainerRequestContext object.

@Test
public void emptyHeader() throws Exception {

    when(context.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn(null);

    filter.filter(context);

    Response r = Response.status(Response.Status.UNAUTHORIZED)
            .type(MediaType.APPLICATION_JSON)
            .entity(ErrorResponse.authenticationRequired())
            .build();

    verify(context).abortWith(eq(r));

}

This test fails on the eq(r) call, even if looking at the string representation of the Response objects they are the same. Any idea what's wrong?

like image 720
agnul Avatar asked Nov 22 '22 09:11

agnul


1 Answers

Since I had the same question, I did it like this:

@Test
public void abort() {

    new MyFilter().filter(requestContext);

    ArgumentCaptor<Response> responseCaptor = ArgumentCaptor.forClass(Response.class);
    verify(requestContext).abortWith(responseCaptor.capture());

    Response response = responseCaptor.getValue();
    assertNotNull(response);
    JerseyResponseAssert.assertThat(response)
            .hasStatusCode(Response.Status.FORBIDDEN);
}
like image 50
McG-work Avatar answered Nov 24 '22 23:11

McG-work