7.14 Testing the Output of a JSP

7.14.1 Problem

You want to test the output of a JSP.

7.14.2 Solution

Write a ServletTestCase that sets up any information the JSP needs to execute and use a RequestDispatcher to forward to the JSP page. The client side endXXX(WebResponse) method can then be used to perform assertions on the content of the JSP, which may be XML, HTML, or any other format that you expect.

7.14.3 Discussion

Testing the output, or result, of a JSP is done using the client side endXXX(WebResponse) method. Example 7-17 shows how to write this test. The first step in writing a test like this is to write a ServletTestCase that sets up any information the JSP needs to generate the content. For example, the JSP may expect a particular object to be in the HttpSession. This information might be retrieved though JDBC or an EJB. If the JSP does not rely on an object retrieved from an external source, or that external source is easily mocked, then Cactus is probably overkill.

Example 7-17. Testing the result of a JSP
package com.oreilly.javaxp.cactus.jsp;

import org.apache.cactus.ServletTestCase;
import org.apache.cactus.WebResponse;

import javax.servlet.RequestDispatcher;

public class SimpleJspTest extends ServletTestCase {

    public SimpleJspTest(String methodName) {
        super(methodName);
    }

    public void testForwardingToJsp(  ) throws Exception {
        // Perform business logic to gather information needed by the
        // JSP. This could be retrieving information from a data store
        // with JDBC or talking with an EJB.
  
        RequestDispatcher rd = this.config.getServletContext(  ).
                getRequestDispatcher("/simple.jsp");
        rd.forward(this.request, this.response);
    }

    public void endForwardingToJsp(WebResponse webResponse) {
        // now assert that the given response contains the information
        // you expect.
    }
}

7.14.4 See Also

Recipe 7.13 describes how to use the endXXX(WebResponse) method with HttpUnit to perform complex assertions on a response. Recipe 7.16 provides information on designing testable JSPs.