开发者

Writing JUNIT for servlet?

开发者 https://www.devze.com 2023-04-09 14:30 出处:网络
I am using glassfish application server. I needto write the junits for some servlet. My question here is how can i create simulated con开发者_运维技巧tainer, mock request and response with core java l

I am using glassfish application server. I need to write the junits for some servlet. My question here is how can i create simulated con开发者_运维技巧tainer, mock request and response with core java libraries or i need to use some kind of tool here ?Any pointers would be helpful?


As hvgotcodes notes, it's entirely possible to write JUnit tests for servlets. But I'd advise you to think carefully before you do so.

Servlets are HTTP request listeners; they run in a servlet container, respond to any HTTP requests that come their way, and package up results to send back. That's all they should be doing, in my opinion. The real work is best left to other objects that the servlet can marshal. These can be POJOs, most likely interface-based, which will mean easier testing without having to start up a servlet container to run the test. If you decide that you need the same functionality in a non-web-based setting, it's easy to do because it already resides in objects other than a servlet.

I'd reconsider the design. Putting a lot of functionality in a servlet might be a bad decision.


1) Its not a bad idea to abstract your application logic into objects that are called by the servlet, so you can test your business logic separate from your servlet interactions.

2) Spring provides some mock classes for tests, including requests and responses. Even if you are not using Spring, you can still use those classes just for tests.


You may find Arquillian from JBoss interesting - http://community.jboss.org/wiki/Arquillian.

Test in-container!

Arquillian provides a easy mechanism to test your application code inside a remote or embedded container or by interacting as a client of the container.

Mission Statement

The mission of the Arquillian project is to provide a simple test harness that developers can use to produce a broad range of integration tests for their Java applications (most likely enterprise applications). A test case may be executed within the container, deployed alongside the code under test, or by coordinating with the container, acting as a client to the deployed code.

0

精彩评论

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