我试着测试这个方法:
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").
你能解释并帮助我吗?感谢
最后一个Mockito.verify(chain, Mockito.times(1)).doFilter(request, response);
失败,因为请求的会话包含键/值"connected",所以doFilter
没有调用。
关于request.getAttribute("connected")
和request.getSession(true).getAttribute("connected")
,我得到了第一个null
,第二个toto
。