An Introduction to Cactus
In its basic form, Cactus is a layer on top of JUnit that allows for test code to be run in both a client space and a server space. Thus, a test can initiate a call from the client, test the server-side code, and review the results. One of the major benefits of Cactus is that it handles all the session creation, request creation, and response creation for meso I can write my tests quickly and consistently.
Example Servlet
The best way to explain how to use Cactus is to set up a simple bean and write tests for it. In this example, I use the following tools:
The first step is to set up the servlet I want to test:
package com.dzrealms.example.servlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import java.io.IOException; /** * A very simple Servlet example */ public class ExampleServlet extends HttpServlet { /** * This method is the entry point for a post from a client. I gather the * parameters being passed in then hand them off to some internal methods. * @param req HttpServletRequest * @param resp HttpServletResponse */ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String variable1 = req.getParameter("variable1"); String variable2 = req.getParameter("variable2"); boolean valid = validate(variable1, variable2); if (!valid) { //forward the user to a page to handle the error req.getRequestDispatcher("someErrorURL").forward(req, resp); return; } //Since it is valid the user should be forward to another jsp. req.getRequestDispatcher("someURL").forward(req, resp); } /** * This method is supposed to validate the data that was received. In this * example it just returns true. * @param var1 First variable to validate * @param var2 Second variable to validate * @return true if the data is valid */ protected boolean validate(String var1, String var2) { //Do something interesting with this method return true; } }
Although this very simple servlet does not do much of anything, it has a method I want to test. Therefore, I want to set up a class that will test the validate method for me.