我该如何测试doFilter方法?

时间:2015-12-12 13:11:03

标签: java junit mockito springmockito

我尝试测试这种方法:

public void doFilter(final ServletRequest request, final ServletResponse response,
    final FilterChain chain) throws IOException, ServletException {

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (httpRequest.getSession(true).getAttribute("connected") == null) {
        httpResponse.sendRedirect(request.getServletContext().getContextPath() + "/");
    } else {
        chain.doFilter(request, response);
    }
}

这是我的测试:

@Test
public void testDoFilter() throws IOException, ServletException {

    MockServletContext servletContext = new MockServletContext();
    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockHttpSession session = new MockHttpSession();
    FilterChain chain = Mockito.mock(FilterChain.class);
    String url = "/private/";
    request.setContextPath("/private/");

    UserFilter userfilter = new UserFilter();
    userfilter.doFilter(request, response, chain);
    Mockito.verify(chain, Mockito.times(0)).doFilter(request, response);
    request.setSession(session);
    request.getSession().setAttribute("connected", "toto");
    Mockito.verify(chain, Mockito.times(1)).doFilter(request, response);
}

但最后一次Mockito.verify没有运行。我什么时候不知道

request.getAttribute("connected")

我在

时获得"toto"null
request.getSession(true).getAttribute("connected").

你能解释一下并帮助我吗? 感谢

1 个答案:

答案 0 :(得分:0)

最后一次Mockito.verify(chain, Mockito.times(1)).doFilter(request, response);失败,因为请求的会话包含键/值"已连接" ,因此doFilter没有&#39}叫来。

request.getAttribute("connected")request.getSession(true).getAttribute("connected")如何,第一个null,第二个toto