How do I Unit Test HTTPServlet?

后端 未结 3 561
说谎
说谎 2021-01-14 18:14

I want to test my servlet with http://www.easymock.org/

How do I write the Unit Testing Code?

I update my code with your responce.

I just used Google

3条回答
  •  一向
    一向 (楼主)
    2021-01-14 18:51

    You need to mock both HttpServletRequest and HttpServletResponse objects. There are existing implementations, easier to use compared to standard mocks.

    Once you have request and response instances, you follow this pattern:

    private final MyServlet servlet = new MyServlet();
    
    @Test
    public void testServlet() {
        //given
        MockHttpServletRequest req = //...
        MockHttpServletResponse resp = //...
    
        //when
        servlet.service(req, resp);
    
        //then
        //verify response headers and body here
    }
    

提交回复
热议问题