1

我在测试 servlet 过滤器时遇到了一些问题。此 servlet 过滤器的目的是在 filterChain 执行后在响应中填充一些 http 标头。所以我要测试的是,在调用 mockFilterChain.doFilter 之前,我的 mockHttpServletResponse 上的 setHeader 调用不会发生。

我正在使用 mockito:mockito-core:1.8.5

所以,这是一个示例代码片段

@Test
public void filterHeaderInjectionHappensLast() throws Exception {
    javax.servlet.Filter myFilter = new HeaderInjectionFilter();

    mockRequest = mock(javax.servlet.http.HttpServletRequest.class);
    mockResponse = mock(javax.servlet.http.HttpServletResponse.class);
    mockFilterChain = mock(javax.servlet.FilterChain.class);

    myFilter.doFilter(mockRequest, mockResponse, mockFilterChain);

    InOrder inOrder = inOrder(mockFilterChain, mockResponse);
    inOrder.verify(mockFilterChain).doFilter(mockRequest,mockResponse);
    inOrder.verify(mockResponse).setHeader(any(String.class),any(String.class));    
}

该测试将无法验证 setHeader 传递任何字符串参数。如果我更改该 setHeader 验证调用以接受代码中使用的特定参数,则测试将成功通过。当您像这样验证订单时,您可以不使用通配符匹配器吗?

HeaderInjectionFilter 看起来像这样

public class HeaderInjectionFilter implements Filter {
    @Override
    public void destroy() {}

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(request, response); //Always doFilter before we add header to response

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader(CACHE_CONTROL, "no-cache");
        httpServletResponse.setHeader(PRAGMA, "no-cache");
    }
}
4

1 回答 1

5

此测试使用 any(String.class) 失败,因为在提供的过滤器实现中,随后两次调用 response.setHeader。inOrder.verify 验证交互是否按顺序发生一次。所以从技术上讲,测试可以更改为

@Test
public void filterHeaderInjectionHappensLast() throws Exception {
    javax.servlet.Filter myFilter = new HeaderInjectionFilter();

    mockRequest = mock(javax.servlet.http.HttpServletRequest.class);
    mockResponse = mock(javax.servlet.http.HttpServletResponse.class);
    mockFilterChain = mock(javax.servlet.FilterChain.class);

    myFilter.doFilter(mockRequest, mockResponse, mockFilterChain);

    InOrder inOrder = inOrder(mockFilterChain, mockResponse);
    inOrder.verify(mockFilterChain).doFilter(mockRequest,mockResponse);
    inOrder.verify(mockResponse, times(2)).setHeader(any(String.class),any(String.class));    
}

或者,测试应该明确地测试设置的特定标头,这是我要走的路径,因为它对于阅读测试的人来说不那么晦涩难懂。

于 2012-12-17T21:25:35.090 回答