Spring MockMvc 重定向不工作

Spring MockMvc redirect not working

我正在尝试使用以下代码模拟 post 请求。

我正在测试 spring 安全登录请求。

MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).addFilter(springSecurityFilterChain)
                .apply(springSecurity())
                .build();

    MvcResult mvcResult = mvc.perform(post("/j_spring_security_check?api=true").param("userName", USERNAME)
                    .param("password", PASSWORD)).andReturn();

代码工作正常,成功登录后,我正在重定向到另一个控制器。

    @Override
        public void onAuthenticationSuccess(HttpServletRequest request,
                HttpServletResponse response, Authentication authentication) throws IOException,
                ServletException {

RequestDispatcher rd = request.getRequestDispatcher("/myURL");
        rd.forward(request, response);

    }

当我 运行 测试时,我得到以下日志。重定向没有发生,映射到 /myURL 的控制器没有被调用。

11:59:55.839 [main] DEBUG o.s.mock.web.MockRequestDispatcher - MockRequestDispatcher: forwarding to [/myURL]
11:59:55.841 [main] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - The HttpSession is currently null, and the HttpSessionSecurityContextRepository is prohibited from creating an HttpSession (because the allowSessionCreation property is false) - SecurityContext thus not stored for next request
11:59:55.841 [main] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed

没有报告错误。

我错过了什么吗?使用 MockMvc 时不会发生重定向吗?

Will redirect not happen while using MockMvc ?

没有。

以下内容直接摘自参考手册的 MockMvc vs End-to-End Tests 部分。

Things that may catch you by surprise are that there is no context path by default, no jsessionid cookie, no forwarding, error, or async dispatches, and therefore no actual JSP rendering. Instead, "forwarded" and "redirected" URLs are saved in the MockHttpServletResponse and can be asserted with expectations.

因此,您所能做的就是验证转发 是否会 发生在真正的 Servlet 容器中,您可以通过调用 andExpect(forwardedUrl("/myURL")) 而不是 andReturn().

注意forwardedUrlMockMvcResultMatchers中的静态方法。