【问题标题】:How to test jersey2 request filters?如何测试 jersey2 请求过滤器?
【发布时间】:2014-12-22 21:38:42
【问题描述】:

在我的 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 对象的字符串表示形式它们是相同的。知道有什么问题吗?

【问题讨论】:

    标签: java unit-testing jersey-2.0


    【解决方案1】:

    我认为您不需要 eq() 方法。您应该验证该上下文。 abortWith(r) 被调用。不过,我可能会遗漏一些东西,因为您没有包含 eq(r) 是什么。

    【讨论】:

    • eq() 来自 Mockito。当然我可以不用它,比如verify(context).abortWith(any()),但是测试将通过所有错误,而不仅仅是UNAUTHORIZED。不是我想要的/我正在测试的。
    • 我的意思是你应该直接将对象放入方法中吧?据我所知,该方法不需要 Matcher。
    【解决方案2】:

    因为我有同样的问题,所以我这样做了:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多