Java Reference
In-Depth Information
If you run this code, you'll find that you've forgotten to set the command to exe-
cute in the HTTP request as a parameter. You need a beginDoGet method to do that,
such as this:
public void beginDoGet(WebRequest request) {
request.addParameter("command", "SELECT...");
}
With this method we're ready to complete the test.
The doGet code is shown in listing 14.8.
Listing 14.8
Implementation of doGet that makes the tests pass
[...]
public class AdminServlet extends HttpServlet {
[...]
public Collection executeCommand(String command) throws Exception {
throw new RuntimeException("not implemented");
}
B
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);
}
}
}
There are two points to note. First, the call to callView isn't present in doGet ; the tests
don't yet mandate it. (They will, but not until we write the unit tests for our JSP .)
Second, we throw a RuntimeException object if executeCommand is called B . We
could return null , but throwing an exception is a better practice. An exception
clearly states that we haven't implemented the method. If the method is called by mis-
take, there won't be any surprises.
JUnit best practice: throw an exception for methods that aren't implemented
When you're writing code, there are often times when you want to execute the
code without having finished implementing all the methods. For example, if you're
writing a mock object for an interface and the code you're testing uses only one
method, you don't need to mock all methods. A good practice is to throw an excep-
tion instead of returning null values (or not returning anything for methods with
no return value). There are two good reasons: doing this states clearly to anyone
reading the code that the method isn't implemented, and it ensures that if the
method is called, it will behave in such a way that you can't mistake skeletal
behavior for real behavior.
 
 
Search WWH ::




Custom Search