2017-08-07 110 views
0

我試圖嘲弄使用下面的代碼POST請求。春天MockMvc重定向不工作

我測試彈簧安全登錄請求。

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時不會發生重定向?

+0

你如何建立MockMvc實例? Spring Security的哪個版本? – holmis83

+0

更新了相關問題的相關細節。我正在使用spring security 4.1.2 – lives

回答

2

會同時使用MockMvc重定向不會發生呢?

NO。

下面從參考手冊的Differences between Out-of-Container and End-to-End Integration Tests部直截取。

事情,可能會出其不意抓住你是有默認情況下,沒有JSESSIONID餅乾,沒有轉發,錯誤或異步分派,因此沒有實際的JSP的渲染沒有上下文路徑。相反,「轉發」和「重定向」網址保存在MockHttpServletResponse中,可以根據預期進行聲明。

因此,所有你能做的就是驗證正向發生在一個真正的Servlet容器,而你做到這一點通過調用andExpect(forwardedUrl("/myURL"))而不是andReturn()

注意forwardedUrlMockMvcResultMatchers一個靜態方法。

+0

感謝您的澄清。 – lives