This tutorial explains how Cactus can be used to test JSP.
There are different kibds of tests that you can implement with Cactus for testing JSP:
endXXX(WebResponse)
method as described in the
TestCase tutorial.
Your test case class will also need to extend
ServletTestCase
and forward the request to your JSP
page, as in the following example:
public class MyTest extends ServletTestCase { [...] public void testXXX() { RequestDispatcher rd = theConfig.getServletContext(). getRequestDispatcher("/path/to/test.jsp"); rd.forward(theRequest, theResponse); } public void endXXX(WebResponse) { // Assert result [...] } [...] }
JspTestCase
. See the
Taglib TestCase
tutorial.
This type of testing depends mostly on your architecture. The general idea is that you would normally have an MVC implementation with a controller (usually a Servlet) that inspect the HTTP request, potentially gather some other data from the Session, ServletContext or some storage and based on this information decides to call some business code logic, and then forward the call to a given JSP page.
Thus, one solution to unit test your JSP in isolation is to succeed in either bypassing the controller altogether or in telling it to use some mock code logic that you would write for your tests.
public class MyTestCase extends JspTestCase { [...] public void beginXXX(WebRequest webRequest) { webRequest.addParameter("cacheId", "1"); } public void testXXX() throws Exception { PageBean bean = new PageBean(); bean.setName("kevin"); request.setAttribute("pageBean", bean); pageContext.forward("/test.jsp"); } public void endXXX(com.meterware.httpunit.WebResponse theResponse) { WebTable table = theResponse.getTables()[0]; assertEquals("rows", 4, table.getRowCount()); assertEquals("columns", 3, table.getColumnCount()); assertEquals("links", 1, table.getTableCell(0, 2).getLinks().length); [...] } }
In testXXX()
, we populate a bean with values for our
test and put this bean in the request. Normally this would have
been performed by the controller but we're bypassing it for the
test. Then we call our JSP page, which looks like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <TITLE>test.jsp</TITLE> </HEAD> <BODY> <P><BR> <jsp:useBean id="pageBean" class="PageBean" scope="request"/> </P> <P> <%= pageBean.getName() %> </P><BR> Place test.jsp's content here </BODY> </HTML>
See the StrutsTestCase project.