I have a servlet called Calculator . It reads the left , right and op parameters and returns, setting the result attribute in the response.
What is the easiest way to unit test this: basically I want to create an HttpServletRequest, set the parameters, and then check the answer - but how to do it?
Here's the servlet code (itβs small and silly for its intended 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);
}
source share