views:

2817

answers:

4

I have a bunch of servlets running under the Tomcat servlet container. I would like to separate test code from production code, so I considered using a test framework. JUnit is nicely integrated into Eclipse, but I failed to make it run servlets using a running Tomcat server. Could you please recommend a unit testing framework that supports testing Tomcat servlets? Eclipse integration is nice but not necessary.

+2  A: 

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

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

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 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.

Will Sargent
A: 

For "in-container" testing, have a look at Cactus

If you want to be able to test without a running container you can either simulate its components with your own mockobjects (e.g. with EasyMock) or you could try MockRunner which has "pre-defined" Stubs for testing servlets, jdbc-connections etc.

Argelbargel
+5  A: 

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.

Scott Bale
+3  A: 

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

http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/mock/web/package-summary.html

WMR