【问题标题】:Spring MockMvc redirect not workingSpring MockMvc 重定向不起作用
【发布时间】:2018-01-14 16:06:39
【问题描述】:

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

我正在测试一个 Spring Security 登录请求。

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 时不会发生重定向吗?

【问题讨论】:

  • 如何构建 MockMvc 实例?哪个版本的 Spring Security?
  • 用相关细节更新了问题。我正在使用 Spring Security 4.1.2

标签: spring-mvc spring-security spring-test spring-test-mvc


【解决方案1】:

使用 MockMvc 时不会发生重定向吗?

没有。

以下内容直接取自参考手册的Differences between Out-of-Container and End-to-End Integration Tests 部分。

您可能会感到惊讶的是,默认情况下没有上下文路径,没有 jsessionid cookie,没有转发、错误或异步调度,因此没有实际的 JSP 呈现。相反,“转发”和“重定向”的 URL 保存在 MockHttpServletResponse 中,并且可以根据预期进行断言。

因此,您所能做的就是验证转发发生在真正的 Servlet 容器中,并且您可以通过调用 andExpect(forwardedUrl("/myURL")) 而不是 andReturn() 来做到这一点。

注意forwardedUrlMockMvcResultMatchers 中的静态方法。

【讨论】:

    猜你喜欢
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 2019-11-26
    • 1970-01-01
    • 2021-01-17
    • 2012-12-31
    相关资源
    最近更新 更多