title: Mocking httpsession for servlet in junit
body: <p>I have servlet which is written below. I need to test the servlet in JUnit. inside the servlet I use <code>HttpSession</code> but when I use my test class, it gives an error. How can I mock <code>HttpSession</code>?</p>
  
  <pre><code>HttpSession session = request.getSession(true);
  
  String Product_id = request.getParameter("productID") ;
  
  DB_Con DB = new DB_Con();
  Statement smt = DB.getStatement();
  
  if ( session.getAttribute("Username") != null &amp;&amp; session.getAttribute("BasketID") != null )
  {
      ...
  }
  </code></pre>
  
  <p>and my unit test is </p>
  
  <pre><code>@Test
  public void testStart()  throws IOException, ServletException
  {
      AddtoBasket AP = new AddtoBasket();
  
      HttpServletRequest request = mock(HttpServletRequest.class);       
      HttpServletResponse response = mock(HttpServletResponse.class);    
      //HttpSession session = mock(HttpSession.class);
      session.setAttribute("Username", "payam");
      session.setAttribute("BasketID", null);
  
      when( request.getParameter("productID") ).thenReturn("300");
      //when( request.getSession(true) ).thenReturn(session);
  
  
      when( session.getAttribute("Username") ).thenReturn("payam");
      when( session.getAttribute("BasketID") ).thenReturn(null);
  
  
  
  
      PrintWriter writer = new PrintWriter("somefile2.txt");
      when(response.getWriter()).thenReturn(writer);
  
      AP.doPost(request,response);
      verify(request, atLeast(1)).getParameter("P_code");
  
      writer.flush(); // it may not have been flushed yet...
      assertTrue(FileUtils.readFileToString(new File("somefile2.txt"), "UTF-8")
                 .contains("Product Added to basket!"));
  }
  </code></pre>