ServletRequest过滤器测试用例

时间:2014-12-15 15:52:06

标签: java unit-testing servlets junit mockito

我有一个看起来像这样的过滤器:

@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请求的最佳方法。

1 个答案:

答案 0 :(得分:2)

您仍然可以使用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);

即使它在内部进行类型转换也很好。