junit测试servlet


用的JUnit是4.1版,easymock-3.1。

 

//简单的servlet程序

public class servletDo extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)

           throws ServletException, IOException {

              doPost( request,  response);
    

    }

    publicvoid doPost(HttpServletRequest request, HttpServletResponse response)

           throws ServletException, IOException {

 

        String name = request.getParameter("username");

        String password = request.getParameter("password");

        System.out.println("username"+name);

        System.out.println("password="+password);

    }

 

     

    publicvoid init()throws ServletException {

       // Put your code here

    }

 

}


 

 

//测试程序

 

public class servletDoTest {

        private servletDo servlet;

         private HttpServletRequest mockRequest;

        private HttpServletResponse mockResponse;

         

        @Before

         public void setUp(){

                   servlet = new servletDo();

                   

                   mockRequest = createMock(HttpServletRequest.class);                          //加载

                   mockResponse = createMock(HttpServletResponse.class);

         } 

         @After

         public void tearDown(){

                   verify(mockRequest);                //验证

                   verify(mockResponse);

         }

         @Test

         public void testDoPostHttpServletRequestHttpServletResponse() {

 

                   mockRequest.getParameter("username");                     

                   expectLastCall().andReturn("allen");//传入参数

                   

                   mockRequest.getParameter("password");            

                   expectLastCall().andReturn("12345");//传入参数

 
                   replay(mockRequest);                                           //回放

                   replay(mockResponse);

                 try {

                            servlet.doPost(mockRequest, mockResponse);

                   } catch (ServletException e) {

                            // TODO Auto-generated catch block

                            e.printStackTrace();

                   } catch (IOException e) {

                            // TODO Auto-generated catch block

                            e.printStackTrace();

                   }        

 

                   //调用

                   assertTrue(true);

                   

         }

 

}

你可能感兴趣的:(junit测试servlet)