HTML and CSS Reference
In-Depth Information
HttpUnit ( ) is another open source JUnit extension designed to test HTML pages.
It is also best suited for Java programmers already using JUnit for test-driven development and is in many ways
quite similar to HtmlUnit. Some programmers prefer HttpUnit, and others prefer HtmlUnit. If there's a difference
between the two, it's that HttpUnit is somewhat lower-level. It tends to focus more on the raw HTTP connection,
whereas HtmlUnit more closely imitates a browser. HtmlUnit has somewhat better support for Java-Script, if
that's a concern. However, there's certainly a lot of overlap between the two projects.
Listing 2.4 demonstrates an HttpUnit test that verifies that a page has exactly one H1 header, and that its text
matches the web page's title. That may not be a requirement for all pages, but it is a requirement for some. For
instance, it would be a very apt requirement for a newspaper site.
Listing 2.4. An HttpUnit Test That Matches the Title to a Unique H1 Heading
import org.xml.sax.SAXException;
import com.meterware.httpunit.*;
import junit.framework.TestCase;
public class TitleChecker extends TestCase {
public void testFormSubmission()
throws IOException, SAXException {
WebConversation wc = new WebConversation();
WebResponse wr = wc.getResponse(
HTMLElement[] h1 = wr.getElementsWithName("h1");
assertEquals(1, h1.length);
String title = wr.getTitle();
assertEquals(title, h1[0].getText());
I could have written this test in HtmlUnit, too, and I could have written Listing 2.3 with HttpUnit. Which one you
use is mostly a matter of personal preference. Of course, these are hardly the only such frameworks. There are
several more, including ones not written in Java. Use whichever one you like, but by all means use something.
JWebUnit is a higher-level API that sits on top of HtmlUnit and JUnit. Generally, JWebUnit tests involve more
assertions and less straight Java code. These tests are somewhat easier to write without a large amount of Java
expertise, and they may be more accessible to a typical web developer. Furthermore, tests can very easily
extend over multiple pages as you click links, submit forms, and in general follow an entire path through a web
Listing 2.5 demonstrates a JWebUnit test for the search engine on my web site. It fills in the search form on the
main page and submits it. Then it checks that one of the expected results is present.
Listing 2.5. A JWebUnit Test for Submitting a Form
Search WWH ::

Custom Search