Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write unit tests for your java servlets?

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?

like image 769
Kico Lobo Avatar asked Dec 04 '09 18:12

Kico Lobo


2 Answers

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)

like image 162
Brian Agnew Avatar answered Sep 20 '22 20:09

Brian Agnew


Almost the same question was asked just today here.

Jakarta cactus is a unit-testing framework for servlets.

like image 20
Bozho Avatar answered Sep 19 '22 20:09

Bozho