title: How to simulate session closing / expiring in Spring Boot tests?
body: <p>I would like to add a couple of tests to the example shown here: </p>
  
  <p><a href="https://spring.io/guides/gs/securing-web/" rel="nofollow noreferrer">https://spring.io/guides/gs/securing-web/</a></p>
  
  <p>to be able to verify that a user can no longer access resources requiring authentication when session closes or expires. I would like to simulate both the following conditions in my tests:</p>
  
  <p>a) the user voluntarily ends their session (e.g. close their browser);</p>
  
  <p>b) the session times out;</p>
  
  <p>I don't know how to reproduce those conditions using MockMvc.</p>
  
  <p>I managed to do the following:</p>
  
  <pre><code>@Test
  public void sessionIsInvalid() throws Exception {
      FormLoginRequestBuilder login = formLogin()
              .user("user")
              .password("password");
  
      mockMvc.perform(login)
              .andExpect(authenticated())
              .andDo(mvcResult -&gt; {
                  MockHttpSession session = (MockHttpSession)mvcResult.getRequest().getSession();
                  session.invalidate();
                  mockMvc.perform(get("/hello")
                          .session(session))
                          .andExpect(status().isFound());
              });
  }
  </code></pre>
  
  <p>...which seems to work but I am not totally sure what <code>invalidate</code> does in this context and whether it matches condition a) above.</p>
  
  <p>To emulate the session timeout, I've done instead:</p>
  
  <pre><code>@Test
  public void sessionExpires() throws Exception {
      FormLoginRequestBuilder login = formLogin()
              .user("user")
              .password("password");
  
      mockMvc.perform(login)
              .andExpect(authenticated())
              .andDo(mvcResult -&gt; {
                  MockHttpSession session = (MockHttpSession)mvcResult.getRequest().getSession();
                  session.setMaxInactiveInterval(1);
                  Thread.sleep(3);
                  mockMvc.perform(get("/hello")
                          .session(session))
                          .andExpect(status().isFound());
              });
  }
  </code></pre>
  
  <p>...but this <strong>doesn't</strong> work. Can someone help me understand what I am doing wrong?</p>