我在测试 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");
}
}