如何模拟类将ServletRequest转换为HttpServletRequest?

时间:2017-05-15 17:16:48

标签: java junit mockito powermock

这是我的代码,

public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    HttpSession session = request.getSession(false);
}

请求使用为null。如何模拟这一行?

1 个答案:

答案 0 :(得分:0)

您应该创建HttpServletRequestHttpServletResponse的模拟,如下所示:

@Test
public void testDoFilter() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    FilterChain filterChain = mock(FilterChain.class);

    Handler handler = new Handler();
    handler.doFilter(request, response, filterChain);

    verify(request).getSession(false);
    // other assertions
}