问题描述
我有一个名为 Calculator
的servlet。它读取参数 left
, right
和 op
并返回通过在响应中设置属性结果
。
I have a servlet called Calculator
. It reads the parameters left
, right
and op
and returns by setting an attribute result
in the response.
对单元测试最简单的方法是什么:基本上我想要的创建一个HttpServletRequest,设置参数,然后检查响应 - 但我该怎么做?
What is the easiest way to unit test this: basically I want to create an HttpServletRequest, set the parameters, and then checking the response - but how do I do that?
这是servlet代码(它的目的很小而且很愚蠢):
Here's the servlet code (it's small and silly on purpose):
public class Calculator extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
public Calculator() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Integer left = Integer.valueOf(request.getParameter("left"));
Integer right = Integer.valueOf(request.getParameter("right"));
Integer result = 0;
String op = request.getParameter("operator");
if ("add".equals(op)) result = this.opAdd(left, right);
if ("subtract".equals(op)) result = this.opSub(left, right);
if ("multiply".equals(op)) result = this.opMul(left, right);
if ("power".equals(op)) result = this.opPow(left, right);
if ("divide".equals(op)) result = this.opDiv(left, right);
if ("modulo".equals(op)) result = this.opMod(left, right);
request.setAttribute("result", result); // It'll be available as ${sum}.
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
...
}
推荐答案
通常,程序的重要逻辑会被分解到其他类中,这些类可以在各种上下文中使用,而不是紧密耦合到Servlet引擎。这使得servlet本身成为Web和应用程序之间的简单适配器。
Often, the important logic of a program is factored out into other classes, that are usable in a variety of contexts, instead of being tightly coupled to a Servlet Engine. This leaves the servlet itself as a simple adapter between the web and your application.
这使程序更容易测试,并且更容易在桌面等其他环境中重用移动应用。
This makes the program easier to test, and easier to reuse in other contexts like a desktop or mobile app.
这篇关于我如何对servlet进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!