繁体   English   中英

如何测试 jersey2 请求过滤器?

[英]How to test jersey2 request filters?

在我的 jersey-2 应用程序中,我使用了一个非常简单的ContainerRequestFilter ,它将检查基本身份验证(可能是重新发明轮子,但请耐心等待)。 过滤器有点像这样

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

现在我想为它编写一个测试,模拟ContainerRequestContext对象。

@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));

}

该测试在eq(r)调用中失败,即使查看Response对象的字符串表示,它们也是相同的。 知道出了什么问题吗?

我不相信你需要eq()方法。 您应该验证该上下文。 abortWith(r)被召唤。 我可能会遗漏一些东西,因为你没有包括eq(r)是什么。

由于我有同样的问题,我是这样做的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM