为 servlet 编写 JUNIT?
我正在使用 glassfish 应用服务器。我需要为一些 servlet 编写 junit。我的问题是如何使用核心 java 库创建模拟容器、模拟请求和响应,或者我需要在这里使用某种工具?任何指针都会有帮助吗?
I am using glassfish application server. I need to write the junits for some servlet. My question here is how can i create simulated container, mock request and response with core java libraries or i need to use some kind of tool here ?Any pointers would be helpful?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 hvgotcodes 所指出的,为 servlet 编写 JUnit 测试是完全可能的。但我建议你在这样做之前仔细考虑一下。
Servlet 是 HTTP 请求监听器;它们在 servlet 容器中运行,响应任何来自它们的 HTTP 请求,并将结果打包并发回。在我看来,这就是他们应该做的。真正的工作最好留给 servlet 可以整理的其他对象。这些可以是 POJO,很可能是基于接口的,这意味着测试更容易,而无需启动 servlet 容器来运行测试。如果您决定在非基于 Web 的设置中需要相同的功能,则很容易做到,因为它已经驻留在 servlet 之外的对象中。
我会重新考虑设计。将大量功能放入 servlet 中可能是一个错误的决定。
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) 将应用程序逻辑抽象为 servlet 调用的对象并不是一个坏主意,因此您可以独立于 servlet 交互来测试业务逻辑。
2)Spring提供了一些 用于测试的模拟类,包括请求和响应。即使您不使用 Spring,您仍然可以使用这些类来进行测试。
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.
您可能会发现 JBoss 的 Arquillian 很有趣 - http://community.jboss.org/wiki/Arquillian 。
You may find Arquillian from JBoss interesting - http://community.jboss.org/wiki/Arquillian.