我在测试 servlet 过滤器时遇到了一些问题。这个 servlet 过滤器的目的是在执行过滤器链后在响应时填充一些 http 标头。 所以我试图测试的是,在我的mockHttpServletResponse上的setHeader调用直到mockFilterChain.doFilter被调用之后才会发生。
我正在使用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 验证调用以接受代码中使用的特定参数,则测试将成功通过。 在验证这样的顺序时,您不能不使用通配符匹配器吗?
标题注入过滤器被简化看起来像这样
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");
}
}
使用 any(String.class) 此测试失败,因为在提供的过滤器实现中,对 response.setHead 进行了两次后续调用。 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));
}
或者,测试应该明确测试设置的特定标头,这是我要走的路径,因为对于阅读测试的人来说,它不那么晦涩难懂。