title: How do I Unit Test a servlet?
body: <p>I have a servlet called <code>Calculator</code>. It reads the parameters <code>left</code>, <code>right</code> and <code>op</code> and returns by setting an attribute <code>result</code> in the response.</p>
  
  <p>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?</p>
  
  <p>Here's the servlet code (it's small and silly on purpose):</p>
  
  <pre><code>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);
      }
  }
  ...
  </code></pre>
  
  <p>}</p>