我有一个名为的servlet Calculator。它读取参数left,right并op通过result在响应中设置属性来返回。
Calculator
left
right
op
result
对此进行单元测试的最简单方法是什么:基本上我想创建一个HttpServletRequest,设置参数,然后检查响应-但是我该怎么做?
这是servlet代码(它小巧而故意):
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 Engine。这使servlet本身成为Web和您的应用程序之间的简单适配器。
这使程序更易于测试,并且更易于在桌面或移动应用程序等其他环境中重用。