Java Reference
In-Depth Information
12.4
Integrating HtmlUnit with Cactus
Cactus
12
is a free, open source test framework for unit testing server-side Java code
including servlets,
EJB
s, and much more. Chapter 14, “Server-side Java testing with
Cactus,” discusses Cactus in detail.
Where does HtmlUnit fit in? Let's look at the various opportunities to test an appli-
cation from the inside out:
JU
nit can test the data tier.
■
Cactus testing takes place in the business middle tier by extending
JU
nit.
■
HtmlUnit lives in the presentation tier.
■
In the standard HtmlUnit unit test scenario, HtmlUnit drives the test. More specifi-
cally,
JU
nit invokes your unit test classes and methods, from which you call HtmlUnit
to emulate a web browser to test your application.
Cactus unit testing manages a different interaction; Cactus calls your HtmlUnit
unit tests at just the right time to verify that the web pages returned to the client. The
main difference here is that HtmlUnit unit testing takes place in-container instead of
through an emulated web client.
To install HtmlUnit in Cactus, see appendix E. For details on managing Cactus
tests with tools like Ant and Maven, we refer you to chapter 14.
12.4.1
Writing tests in Cactus
Because HtmlUnit tests normally work with HtmlPage objects, we need to plug into
the Cactus test execution at the point where a page is about to be returned to the
client. Cactus tests for Java-based code like servlets are subclasses of
org.apache.
cactus.ServletTestCase
. If the test class contains a method whose name starts
with
end
, Cactus will call this method with a
WebResponse
, which contains the con-
tents of the server's response. Take great care to import the appropriate
Web-
Response
class for your tests, because three variations are supported:
■
com.meterware.httpunit.WebResponse
for HtmlUnit 1.6
■
com.gargoylesoftware.htmlunit.WebResponse
for HtmlUnit 2.7
■
org.apache.cactus.WebResponse
for Cactus itself
Your boilerplate test class should look like listing 12.11.
Listing 12.11
Boilerplate HtmlUnit
ServletTestCase
subclass
[...]
public class
HtmlUnitServletTestCase
extends
ServletTestCase {
public static
Test suite() {
return new
TestSuite(HtmlUnitServletTestCase.class);
}
12
Cactus site:
http://jakarta.apache.org/cactus/