Java Reference
In-Depth Information
Listing 8.1
Servlet implementing
isAuthenticated
[...]
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();
}
}
This servlet, although simple enough, allows us to show the limitation of standard
unit testing. In order to test the method
isAuthenticated
, we need a valid
Http-
ServletRequest
. Because
HttpServletRequest
is an interface, we can't just call a
new
HttpServletRequest
. The
HttpServletRequest
lifecycle and implementation
are provided by the container (in this case, a servlet container.) The same is true for
other server-side objects like
HttpSession
.
JU
nit alone isn't enough to write a test
for the
isAuthenticated
method and for servlets in general.
DEFINITION
Component
and
container
—In this chapter, a
component
executes in
a container. A
container
offers services for the components it's hosting, such as
lifecycle, security, transaction, distribution, and so forth.
In the case of servlets and
JSP
s, the container is a servlet container like Jetty or Tomcat.
There are other types of containers, for example,
EJB
, database, and
OSG
i containers.
As long as a container creates and manages objects at runtime, we can't use stan-
dard
JU
nit techniques to test those objects.
8.2
The mock objects solution
We look at several solutions for in-container testing. The first solution for unit testing
the
isAuthenticated
method (listing 8.1) is to mock the
HttpServletRequest
class
using the approach described in chapter 7. Although mocking works, we need to write
a lot of code to create a test. We can achieve the same result more easily using the
open source EasyMock
1
framework (see chapter 7), as listing 8.2 demonstrates.
1