开发者

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开发者_如何学Python some dificulty: how do you unit test your java servlets?


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)


Almost the same question was asked just today here.

Jakarta cactus is a unit-testing framework for servlets.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜