Java Reference
In-Depth Information
public HtmlUnitServletTestCase(String name) {
super (name);
}
public void end(WebResponse webResponse) {
// asserts
}
public void test() throws ServletException {
SampleServlet servlet = new SampleServlet();
servlet.init( this .config);
// asserts
}
}
There are a couple of things to note in this example:
The ServletTestCase provides the following instance variables for your use:
AbstractServletConfigWrapper config
AbstractHttpServletRequestWrapper request
HttpServletResponse response
HttpSession session
The test method creates the servlet to test and initializes it.
Cactus integrates with JU nit 3; it doesn't provide JU nit 4 niceties.
Cactus tip
If your test class doesn't contain a begin method, the end method name must be
end . If your test class includes a begin method, the end method name must match,
for example, beginFoo and endFoo ; otherwise the end method won't be called.
Next, let's create the simple servlet in listing 12.12.
Listing 12.12
A simple servlet
[...]
public class SampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Hello
World</title></head><body><p>Hello World</p></body></html>");
}
}
This servlet returns an HTML document with a title and a single paragraph. The next
step is to flesh out our end method; we need to get an HtmlPage from the WebResponse
argument and validate its contents. Getting an HtmlPage from a WebResponse requires
parsing the HTML . To do so, we use the HtmlUnit HTMLParser class:
 
 
 
Search WWH ::




Custom Search