Java Reference
In-Depth Information
Before we begin coding the test, let's review the requirement for
AdminServlet
. The
servlet should extract the needed parameter containing the command to execute
from the
HTTP
request (in this case, the
SQL
command to run). Then it should fetch
the data using the extracted command. Finally, it should pass the control to the
JSP
page for display, passing the fetched data. Let's call the methods corresponding to
these actions
getCommand
,
executeCommand
, and
callView
, respectively.
D
ESIGNING
THE
FIRST
TEST
Listing 14.3 shows the unit tests for the
getCommand
method. Remember that we
haven't yet written the code under test. The
AdminServlet
class doesn't exist, and our
code doesn't compile (yet).
Listing 14.3
Designing and testing the
getCommand
method
[...]
import
javax.servlet.ServletException;
import
org.apache.cactus.ServletTestCase;
import
org.apache.cactus.WebRequest;
B
public
class
TestAdminServlet
extends
ServletTestCase {
public
void
beginGetCommandOk(WebRequest request) {
request.addParameter("command", "SELECT...");
}
C
public
void
testGetCommandOk()
throws
Exception {
AdminServlet servlet =
new
AdminServlet();
String command = servlet.getCommand(request);
assertEquals("SELECT...", command);
}
D
public
void
testGetCommandNotDefined {
AdminServlet servlet =
new
AdminServlet();
try
{
servlet.getCommand(request);
fail("Command should not have existed");
}
catch
(ServletException expected) {
assertTrue(
true
);
}
}
}
This is a typical Cactus test case. We extended the
ServletTestCase
B
, because the
component that we want to test is a servlet. We also set a request parameter in
the
begin
XXX
method
C
that we assert to be present in the
test
XXX
method
D
.
Once we've written the test case, we can go on and implement the bare minimum
of code that will allow us to compile the project. We need to implement a sample serv-
let with a
getCommand
method. Listing 14.4 shows the code.