Testing the Output of a JSP
Problem
You want to test the output of a JSP.
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.
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 ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access