我有一个过滤器,看起来像这样:
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// Get the servlet request
HttpServletRequest req = (HttpServletRequest) request;
... Some logic code here ...
if (!accepted.contains(req.getRequestURI())) {
HttpServletResponse res = (HttpServletResponse) response;
res.sendError(404, "Some Error");
return;
}
// Pass the request along the filter chain
chain.doFilter(request, response);
}
问题出在我的测试用例上。通常我会使用 mockito 来模拟HttpServletRequest
这样的东西:
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURI()).thenReturn("the test URI");
但是,HttpServletRequest
是通过强制转换在方法内部获得的,我不确定测试各种 URI 请求的最佳方法。
你应该仍然可以使用 doFilter 调用你的 servlet,如下所示:
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURI()).thenReturn("the test URI");
HttpServletResponse response = mock(HttpServletResponse.class);
//mock method calls on response, replay
myServlet.filter(request, response);
即使它在内部进行类型转换也没关系。