Java Reference
In-Depth Information
Listing 14.4
Minimum code to make the
TestAdminServlet
compile
[...]
public
class
AdminServlet
extends
HttpServlet {
public
String
getCommand(HttpServletRequest request)
throws
ServletException {
return
null
;
}
}
This is the minimum code that allows the
TestAdminServlet
to compile successfully.
The code compiles okay, but there's one more thing that we have to think about.
What you probably notice at this point is that if this test gets executed it will fail,
because of the
null
object that we return. Tests are used to prevent us from making
mistakes. That said, we always have to ensure that tests fail if we provide corrupt data,
as in the previous example. At this point, we need to ensure that the error is reported
successfully. And after that, when we implement the code under test, the tests should
succeed, and we'll know we've accomplished something. It's a good practice to ensure
that the tests fail when the code fails.
JUnit best practice: always verify that the test fails when it should fail
It's a good practice to always verify that the tests you're writing work. Be sure a
test fails when you expect it to fail. If you're using the test-driven development
methodology, this failure happens as a matter of course. After you write the test,
write a skeleton for the class under test (a class with methods that return
null
or
throw runtime exceptions). If you try to run your test against a skeleton class, it
should fail. If it doesn't, fix the test (ironically enough) so that it does fail! Even
after the case is fleshed out, you can vet a test by changing an assertion to look
for an invalid value that should cause it to fail.
But let's get back to the test. Listing 14.5 shows the code for
getCommand
. It's a mini-
mal implementation that passes the tests.
Listing 14.5
Implementation of
getCommand
that makes the tests pass
[...]
public
String getCommand(HttpServletRequest request)
throws
ServletException {
String command = request.getParameter(COMMAND_PARAM);
if
(command ==
null
) {
throw
new
ServletException("Missing parameter ["
+ COMMAND_PARAM + "]");
}
return
command;
}
[...]