Unit testing a Java Servlet

后端 未结 8 1731
心在旅途
心在旅途 2020-11-28 21:05

I would like to know what would be the best way to do unit testing of a servlet.

Testing internal methods is not a problem as long as they don\'t refer to the servl

8条回答
  •  臣服心动
    2020-11-28 21:37

    Are you calling the doPost and doGet methods manually in the unit tests? If so you can override the HttpServletRequest methods to provide mock objects.

    myServlet.doGet(new HttpServletRequestWrapper() {
         public HttpSession getSession() {
             return mockSession;
         }
    
         ...
    }
    

    The HttpServletRequestWrapper is a convenience Java class. I suggest you to create a utility method in your unit tests to create the mock http requests:

    public void testSomething() {
        myServlet.doGet(createMockRequest(), createMockResponse());
    }
    
    protected HttpServletRequest createMockRequest() {
       HttpServletRequest request = new HttpServletRequestWrapper() {
            //overrided methods   
       }
    }
    

    It's even better to put the mock creation methods in a base servlet superclass and make all servlets unit tests to extend it.

提交回复
热议问题