1

I have created a simple calculator using java servlets, and I have been told to test it with JUNIT.

How do I test servlets with http responses and such, could some one give me an example of a test?

This is an example of my code, parameters are submitted by a form in html;

package NipenderSoft;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LaskuriServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter temp = response.getWriter();
    }

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

            int luku01= Integer.parseInt(request.getParameter("luku01"));
            int luku02= Integer.parseInt(request.getParameter("luku02"));
            int ans = 0;

            if(request.getParameter("toiminto").equals("plus"))
            {
                ans = luku01+luku02;
            }
            if(request.getParameter("toiminto").equals("miinus"))
            {
               ans = luku01-luku02;
            }
            if(request.getParameter("toiminto").equals("kerto"))
            {
               ans = luku01*luku02;
            }if(request.getParameter("toiminto").equals("jako"))
            {
               ans = luku01/luku02;
            }

            response.getWriter().println(ans); 
        }

2 Answers2

1

As instance of HttpRequest is created at runtime by servlet container like tomcat etc. So either you have to write your own logic to extend HttpRequest and provide implementation but that lots of work. Would suggest using framework like easymock see see How do I Unit Test HTTPServlet?

just for information , if you go for struts 2 , you can design your action class independent of HTTP classes and hence great for unit testing POV.

Community
  • 1
  • 1
M Sach
  • 33,416
  • 76
  • 221
  • 314
1

I don't think this is a good candidate for a unit test. The clue is that you have to have a servlet container running to test it.

This is not a good design. You should not have hand coded HTML and style information streamed out of a servlet.

Whatever this class is doing, a better design would put the behavior in a POJO that you could exercise without starting a servlet container.

A more modern UI approach would call this servlet as a REST service using an AJAX call and update the UI dynamically. The UI would consist of HTML5, CSS3, and JavaScript.

duffymo
  • 305,152
  • 44
  • 369
  • 561