Java Reference
In-Depth Information
Listing 14.7
Implementation of
callView
that makes the test pass
[...]
public
class
AdminServlet
extends
HttpServlet {
[...]
public
void
callView(HttpServletRequest request) {
request.getRequestDispatcher("/results.jsp")
.forward(request, response);
}
}
We don't have a test yet for the returned result, so not returning anything is enough.
That will change once we test the
JSP
.
T
ESTING
THE
DO
G
ET
METHOD
Let's design the unit test for the
AdminServlet
doGet
method. To begin, we need
to verify that the test results are put in the servlet request as an attribute. Here's
how to do that:
Collection results = (Collection) request.getAttribute("result");
assertNotNull("Failed to get execution results from the request",
results);
assertEquals(2, results.size());
This code leads to storing the command execution result in
doGet
. But where do we
get the result? Ultimately, from the execution of
executeCommand
—but it isn't imple-
mented yet. The typical solution to this kind of deadlock is to have an
execute-
Command
that does nothing in
AdminServlet
. Then, in our test, we can implement
executeCommand
to return whatever we want:
AdminServlet servlet = new AdminServlet() {
public Collection executeCommand(String command) throws Exception {
return createCommandResult();
}
};
We can now store the result of the test execution in
doGet
:
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
try {
Collection results = executeCommand(getCommand(request));
request.setAttribute("result", results);
} catch (Exception e) {
throw new ServletException("Failed to execute command", e);
}
}
Notice that we need the
catch
block because the servlet specification says
doGet
must
throw a
ServletException
. Because
executeCommand
can throw an exception, we
need to wrap it into a
ServletException
.