views:

119

answers:

3

Hi,

what are the best practices to unit test java servlets? By the way: this is a topic in which I have some dificulty: how do you unit test your java servlets?

+2  A: 

Almost the same question was asked just today here.

Jakarta cactus is a unit-testing framework for servlets.

Bozho
Good to know this Jakarta cactus project. But I whould like to know also what are the best practices.Thanks for the tip!
Kico Lobo
+14  A: 

The most important thing to do is to try and extract everything from the servlets that isn't directly related to servlet behaviour.

This immediately makes testing core functionality a lot easier. By doing this you immediately have a set of components not tied to the container and testable without the pain of running and interfacing to a container (besides making them more reusable). Some thought should be given to architecture and the appropriate layering of components - e.g. components returning object structures rather than displayable fragments, not making use of HttpRequests directly but some request marshalling structure etc.

The majority of your tests (dependent on your system structure and complexity) can be tested normally. Additional servlet-focused tests can be built using (say) Apache Cactus to sanity check functionality. Beyond that you may wish to investigate in-browser solutions such as Selenium.

(Note: This approach works for most GUI environments - e.g. Swing)

Brian Agnew
+2  A: 

What we normally do is load the servlet with a mock request and response. If you're using Spring, this is especially easy since it actually provides a MockHttpRequest and MockHttpResponse.

Assuming you have clearly defined layers in your application, the rest is easy. The underlying service / DAO layer can be replaced with mocks, so we just make sure the servlet is doing what its supposed to be doing for the given request object, and writing the response correctly.

Sudhir Jonathan