Java Reference
In-Depth Information
mailing list ask if people can use Cactus for testing an application based on a spe-
cific framework (like Struts,
JSF
, or Spring). There are quite a few tools dedicated to
such testing, and we cover some of them later in the topic. Most of those tools are
based on Cactus and require Cactus in their classpath, but again Cactus is designed
for in-container testing of the components from the Java
EE
spec.
14.2.2
General principles
Because Cactus is an extension of
JU
nit, every Cactus test is a
JU
nit test by itself.
The reverse isn't true; most of the
JU
nit tests are Cactus tests. So what distinguishes
the Cactus tests from the
JU
nit tests? You need to stick to a couple of rules in order
to use Cactus.
We already discussed in chapter 8 what in-container testing means. Back then, we
had a web application that uses servlets. We want to unit test the
isAuthenticated
method in listing 14.1 from a
SampleServlet
servlet.
Listing 14.1
Sample of a servlet method to unit test
[...]
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpSession;
public
class
SampleServlet
extends
HttpServlet {
public
boolean
isAuthenticated(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if
(session ==
null
) {
return
false
;
}
String authenticationAttribute =
(String) session.getAttribute("authenticated");
return
Boolean.valueOf(authenticationAttribute).booleanValue();
}
}
In order to be able to test this method, we need to get hold of a valid
HttpServlet-
Request
object. Unfortunately, it isn't possible to call
new
HttpServletRequest
to cre-
ate a usable request. The lifecycle of
HttpServletRequest
is managed by the container.
JU
nit alone isn't enough to write a test for the
isAuthenticated
method.
So what must we do in order to obtain a valid
HttpServletRequest
? Wouldn't it be
perfect if we had an
HttpServletRequest
object already instantiated in our test cases?
And how can we achieve this? What if we always had to extend a certain class that takes
care of providing us the server-side objects that are otherwise managed by the con-
tainer (such as
HttpServletRequest
)? Listing 14.2 shows a corresponding Cactus test
that tests the given servlet.