How do I Unit Test HTTPServlet?

后端 未结 3 535
说谎
说谎 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:46

    I am more familiar with Mockito, but I believe they are still similar. In fact I think Mockito was branched from EasyMock a few years back.

    There is no cookbook approach to unit testing, but this is the basic approach I tend to take:

    1) Create a real instance of your servlet class (i.e. new MyServlet())

    2) Create a mock HttpRequest using EasyMock

    2a) Mock the desired behavior of the request to simulate a real HTTP request. For example, this may mean you simulate the presence of request parameters or headers.

    3) Create a mock HttpResponse using EasyMock

    4) call the doGet() method of your servlet passing it both the mock request and response.

    5) For verification, inspect the mock HttpResponse. Verify that: (a) the expected methods have been called on the object, (b) The expected data has been passed to the object.

    I know this is very high-level, but I am just outlining the approach. I assume you know how to accomplish the mocking/verification behaviors using EasyMock.

    Hope this is helpful.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2021-01-14 18:51

    I prefer using spring-test and the MockHttpServletRequest and MockHttpServletResponse. They are more stub like than mocks, but work really well.

    This answer has information regarding the usage: How to test my servlet using JUnit

    0 讨论(0)
提交回复
热议问题