How do you write unit tests for your Java servlets?

What are the best practices for unit test Java servlets? By the way: this is a topic in which I have some kind of dificulty: how do you unit test your Java servlets?

+6
java unit-testing servlets
source share
3 answers

The most important thing is to try to extract all of the servlets that are not directly related to the behavior of the servlets.

This immediately simplifies testing core functionality. By doing so, you will immediately receive a set of components that are not attached to the container and that are tested without pain when working and interacting with the container (in addition to making them more reusable). You need to think about the architecture and the corresponding bundle of components - for example, components that return object structures, not displayed fragments, without using HttpRequests directly, but some query sorting structures, etc.

Most of your tests (depending on your structure and system complexity) can be tested normally. Additional servlet-oriented tests can be built using (say) Apact Cactus to test health. In addition, you can explore solutions in the browser, such as Selenium .

(Note: This approach works for most GUI environments — for example, Swing)

+17
source share

Almost the same question was asked only today here .

Jakarta cactus is a single platform for servlets.

+2
source share

What we usually do is load a servlet with a mock request and response. If you use Spring, this is especially convenient as it actually provides MockHttpRequest and MockHttpResponse.

Assuming your application has clearly defined levels, the rest is easy. The main layer of the / DAO service can be replaced with mocks, so we just make sure that the servlet does what it should do for this request object, and wrote the answer correctly.

+2
source share

All Articles