Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在junit中模拟servlet的httpsession_Java_Unit Testing_Servlets_Junit - Fatal编程技术网

Java 在junit中模拟servlet的httpsession

Java 在junit中模拟servlet的httpsession,java,unit-testing,servlets,junit,Java,Unit Testing,Servlets,Junit,我有一个servlet,它写在下面。我需要在JUnit中测试servlet。在servlet内部,我使用了HttpSession,但是当我使用测试类时,它会给出一个错误。如何模拟HttpSession HttpSession session = request.getSession(true); String Product_id = request.getParameter("productID") ; DB_Con DB = new DB_Con(); Statement smt = D

我有一个servlet,它写在下面。我需要在JUnit中测试servlet。在servlet内部,我使用了
HttpSession
,但是当我使用测试类时,它会给出一个错误。如何模拟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 )
{
    ...
}
我的单元测试是

@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!"));
}

也许可以取消对测试中两行注释掉的行的注释?否则你必须准确地说出你所犯的错误。不知道错误,很难回答。给出一个错误??请指定错误。同时发布
AP.doPost(请求、响应)的完整代码