HTML and CSS Reference
In-Depth Information
HtmlUnit provides two main advantages over pure JUnit.
The WebClient class makes it much easier to pretend to be a web browser.
The HTMLPage class has methods for inspecting common parts of an HTML document.
For example, HtmlUnit will run JavaScript that's specified by an onLoad handler before it returns the page to the
client, just like a browser would. Simply loading the page with an XML parser as Listing 2.2 did would not run
the JavaScript.
Listing 2.3 demonstrates the use of HtmlUnit to check that all the links on a page are not broken. I could have
written this using a raw parser and DOM, but it would have been somewhat more complex. In particular,
methods such as getAnchors to find all the a elements in a page are very helpful.
Listing 2.3. An HtmlUnit Test for a Page's Links
Code View:
import java.util.*;
import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
import junit.framework.TestCase;
public class LinkCheckTest extends TestCase {
public void testBlogIndex()
throws FailingHttpStatusCodeException, IOException {
WebClient webClient = new WebClient();
URL url = new URL("");
HtmlPage page = (HtmlPage) webClient.getPage(url);
List links = page.getAnchors();
Iterator iterator = links.iterator();
while (iterator.hasNext()) {
HtmlAnchor link = (HtmlAnchor);
URL u = new URL(link.getHrefAttribute());
// Check that we can download this page.
// If we can't, getPage throws an exception and
// the test fails.
This test is more than a unit test. It checks all the links on a page, whereas a real unit test would check only
one. Furthermore, it makes connections to external servers. That's very unusual for a unit test. Still, this is a
good test to have, and it will let us know that we need to fix our pages if an external site breaks links by
reorganizing its pages.
Search WWH ::

Custom Search