title: Mocking HttpSession using Mockito
body: <p>I need to test the following controller method:</p>
  
  <pre class="lang-java prettyprint-override"><code>@RequestMapping(value="/addLocation")
  public String addLocation(HttpServletRequest request, HttpSession session) {
  
      String location = (String) request.getParameter("plz_ort");
      String radius = (String) request.getParameter("umkreis");
  
      ((ArrayList&lt;String&gt;) session.getAttribute("queryTopics")).clone();        
  
      ...
  }
  </code></pre>
  
  <p>Therefor I wrote this test class using Mockito and JUnit</p>
  
  <pre><code>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
  
  import java.util.ArrayList;
  
  import org.junit.Before;
  import org.junit.Ignore;
  import org.junit.Test;
  import org.mockito.InjectMocks;
  import org.mockito.Mock;
  import org.mockito.MockitoAnnotations;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.mock.web.MockHttpSession;
  import org.springframework.test.web.servlet.MockMvc;
  import org.springframework.test.web.servlet.setup.MockMvcBuilders;
  
  public class MyControllerTest {
  
  
      @InjectMocks
      private MyController myController;
  
      private MockMvc mockMvc;
  
      @InjectMocks
      MockHttpSession session;
  
      @Before
      public void setup() {
  
          // Process mock annotations
          MockitoAnnotations.initMocks(this);
  
          // Setup Spring test in standalone mode
          this.mockMvc = MockMvcBuilders.standaloneSetup(MyController)
                  .build();
  
      }
  
      @Test
      public void addLocation_StatusOK() throws Exception {
          session.setAttribute("queryTopics", new ArrayList&lt;String&gt;(0));
  
          this.mockMvc.perform(
                  post("/addLocation")
                          .param("plz_ort", "PLZ ORT")
                          .param("umkreis", "5"))
                  .andExpect(
                          status().isOk());
  
      }
  
  }
  </code></pre>
  
  <p>As you can see I need to mock the session when running this test.
  When I debug through the code and stop at the line <code>session.setAttribute("queryTopics", new ArrayList&lt;String&gt;(0));</code> the session object is <code>org.springframework.mock.web.MockHttpSession@5583d693</code> (containing a attributes hash map <code>{queryTopics=[]}</code>), so I think that's fine.
  However the session object of my next breakpoint in line <code>((ArrayList&lt;String&gt;) session.getAttribute("queryTopics")).clone();</code> is <code>org.springframework.mock.web.MockHttpSession@7545a27f</code>.</p>
  
  <p>At least it's the correct type (<code>MockHttpSession</code>) but it's got a different ID so it's actually a whole new object and thus doesn't contain the session attributes from the test.</p>
  
  <p>Could you please help me out on this one?</p>