Rectangle 27 0

eclipse Unit testing servlets?


public void testPost() {
   mockRequest = createMock(HttpServletRequest.class);
   mockResponse = createMock(HttpServletResponse.class);
   replay(mockRequest, mockResponse);
   myServlet.doPost(mockRequest, mockResponse);
   verify(mockRequest, mockResponse);
}

Note that if you want to use EasyMock with classes, you'll have to use the EasyMock class extension library. But it'll work the same way from then on.

Okay. Ignoring the 'tomcat' bit and coding to the servlet, your best bet is to create mocks for the response and request objects, and then tell it what you expect out of it.

So for a standard empty doPost, and using EasyMock, you'll have

Then start adding code to the doPost. The mocks will fail because they have no expectations, and then you can set up the expectations from there.

Note
Rectangle 27 0

eclipse Unit testing servlets?


Check out ServletUnit, which is part of HttpUnit. In a nutshell, ServletUnit provides a library of mocks and utilities you can use in ordinary JUnit tests to mock out a servlet container and other servlet-related objects like request and response objects. The link above contains examples.

The HttpUnit project seems to have had no activity since 2008-05. Perhaps it is dead?

Note
Rectangle 27 0

eclipse Unit testing servlets?


The Spring Framework has nice ready made mock objects for several classes out of the Servlet API:

Note
Rectangle 27 0

eclipse Unit testing servlets?


  • Finally, if you feel it really is necessary, you can do integration tests using a too such as HtmlUnit or JWebUnit .
  • You can test the presentation layer, as others suggest, using mock HTTP request and response objects.
  • You can unit test the first two layers without any servlet stuff at all; it will be easier to test that way.

Separate the parts of that code that deal with HTTP requests and response from the parts that do business logic or data-base manipulation. In most cases this will produce a three tier architecture, with a data-layer (for the data-base/persistence), service-layer (for the business logic) and a presentation-layer (for the HTTP requests and responses).

Note