I have servlet which is written below. i need to test the servlet in junit. inside the servlet i use http session but when i use my test class , give an error how can i mock httpsession ? 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 && session.getAttribute("BasketID") != null )
{
....
}
and my unit test is
@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!"));
}
Aucun commentaire:
Enregistrer un commentaire