Java Reference
In-Depth Information
To illustrate the challenge and highlight the dependencies that need to be mocked during
testing, let me start with a simple servlet class, written in Java, called HelloServlet :
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print("Hello, Servlet!");
}
}
Servlets are all created by inheritance, normally by extending javax.servlet.http
.HttpServlet . HttpServlet is an abstract class with no abstract methods. It re-
ceives HTTP requests and delegates them to a do method corresponding to each HTTP
verb, like doGet , doPost , doPut , doTrace , or doOptions . Each of these methods
takes two arguments, one of type HttpServletRequest and one of type HttpSer-
vletResponse .
The HelloServlet class overrides the doGet method to respond to HTTP GET re-
quests. It uses the resp argument (an instance of HttpServletResponse ) to get the
associated output writer, which is used to print to the output stream.
Even in a class this simple, it's apparent that unit testing is going to be a challenge. As a
reminder of what unit testing is all about, let me say this:
Unit-Testing Web Components
The goal of unit-testing web applications is to run tests outside of a container. This requires
mock objects for all the container-provided classes and services.
In this case I need objects representing the two arguments of type HttpServlet-
Request and HttpServletResponse . In most cases I'll also need objects represent-
ing HttpSession , ServletContext , and possibly more.
This is where the set of mock classes from the Spring framework helps. The Spring API in-
cludes a package called org.springframework.mock.web that, as described in the
API, contains “a comprehensive set of Servlet API 2.5 [ 3 ] mock objects, targeted at usage
Search WWH ::




Custom Search