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

Java 如何模拟将ServletRequest转换为HttpServletRequest的类?,java,junit,mockito,powermock,Java,Junit,Mockito,Powermock,这是我的密码 public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletRes

这是我的密码

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);
}

请求被使用为空。如何模拟这些行?

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

@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
}

嗯,你说的“模仿”是什么意思?模拟实例是测试代码的一部分,而不是运行代码的一部分。您需要传递实际的实例化对象。您使用的模拟框架是什么?我猜,要么你在测试代码中创建一个真实的实例,要么在调用
doFilter
方法时通过?@SabirKhan ya必须通过真实的实例我将如何通过你能给我发送链接或任何适当的例子吗?