Java Reference
In-Depth Information
So far, we've discussed the Administrator application and shown how to test one part
of it, the servlet part. Now it's time to move on and concentrate on probably the most
difficult-to-test part of the application, the frontend.
14.4
Testing JSPs
In this section, we continue with the Administration application we introduced in the
previous section. Here, we concentrate on testing the view components—namely
the JavaServer Pages (
JSP
s).
14.4.1
Revisiting the Administration application
We call the application by sending an
HTTP
request (from our browser) to the
Admin-
Servlet
(figure 14.2). We pass a
SQL
query to run as an
HTTP
parameter, which is
retrieved by the
AdminServlet
. The security filter intercepts the
HTTP
request and
verifies that the
SQL
query is harmless (it's a
SELECT
query). Then, the servlet executes
the query on the database, stores the resulting objects in the
HTTP
Request
object,
and calls the Results View page. The
JSP
takes the results from the
Request
and dis-
plays them, nicely formatted, using custom
JSP
tags from our tag library.
14.4.2
What is JSP unit testing?
First, let's remove any doubt: what we call
unit testing a
JSP
isn't about unit testing the
servlet that's generated by the compilation of the
JSP
. We also assume that the
JSP
is
well designed, which means there's no Java code in it. If the page must handle any
presentation logic, the logic is encapsulated in a JavaBean or in a taglib. We can per-
form two kinds of tests to unit test a
JSP
: test the
JSP
page itself in isolation and/or test
the
JSP
's taglibs.
We can isolate the
JSP
from the backend by simulating the JavaBeans it uses and
then verifying that the returned page contains the expected data. We use Cactus to
demonstrate this type of test. Because mock objects (see chapter 7) operate only on
Java code, we can't use a pure mock objects solution to unit test our
JSP
in isolation.
We could also write functional tests for the
JSP
using a framework such as HttpUnit.
But doing so means going all the way to the backend of the application, possibly to
the database. With a combination of Cactus and mock objects, we can prevent call-
ing the backend and keep our focus on unit testing the
JSP
s themselves. We can also
unit test the custom tags used in the
JSP
.
14.4.3
Unit testing a JSP in isolation with Cactus
The strategy for unit testing
JSP
s in isolation with Cactus is defined in figure 14.3.
Here's what happens. The Cactus test case class must extend
ServletTestCase
(or
JspTestCase
):
In the
test
XXX
method (called by Cactus from inside the container), we cre-
ate the mock objects that will be used by the
JSP
. The
JSP
gets its dynamic
1