MockMvc执行'get'不创建JSESSIONID cookie

时间:2018-04-03 14:05:44

标签: java spring junit httpsession mockmvc

我尝试使用MockMvc测试我的安全层。我写了以下集成测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationContextConfig.class,WebSecurityConfig.class})
@WebAppConfiguration
public class AuthenticationStatesIT {

  @Autowired
  private WebApplicationContext context;

  private MockMvc mockMvc;

  @Before
  public void initMocks(){

     this.mockMvc = MockMvcBuilders.webAppContextSetup(context)
           .addFilter(new AuthenticationFilter(), "/*")
           .build();
   }

  @Test
  public void stage10_firstRequestForLoginPageShouldReturnProperPageAndAddUnauthenticatedStateToSession () throws Exception {

      MvcResult mvcResult = mockMvc.perform(get("/"))
                             .andDo(print())
                             //.andExpect(cookie().exists("JSESSIONID"))
                             .andExpect(status().is3xxRedirection()).andReturn();

      MockHttpSession session = (MockHttpSession) mvcResult.getRequest().getSession();


      StatesAuthenticator authenticator = (StatesAuthenticator)session.getAttribute("authenticator");
      AuthenticationState state = authenticator.getState();

      Assert.assertNotNull(authenticator);
      Assert.assertNotNull(state);
  }

}

除了一个细节外,一切正常。 'JSESSIONID'cookie没有创建。我确信新会话已创建,但测试'andExpect(cookie()。exists(“JSESSIONID”))'未通过。我正在创建会话如下:

public class UnauthenticatedState implements AuthenticationState {

  @Override
  public void doAuthentication(StatesAuthenticator authentication,ServletRequest request, 
        ServletResponse response,FilterChain chain) throws IOException, ServletException {

     authentication.setAuthentication(null);

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

      //get the old session and invalidate if exists
       HttpSession oldSession = httpRequest.getSession(false);
       if (oldSession != null) {
           oldSession.invalidate();
       }
       //generate a new session
       HttpSession session = httpRequest.getSession(true);
       session.setMaxInactiveInterval(300); // 5 minutes
     session.setAttribute("authenticator", authentication);

     authentication.setState(new AuthenticatingState());

     httpResponse.sendRedirect("login");
  }

}

当我运行服务器并在浏览器中查找该cookie时,一切正常,cookie就存在了。有人可以解释一下为什么MockMvc没有设置'JSESSIONID'吗?谢谢你的帮助!

0 个答案:

没有答案