Java Reference
In-Depth Information
Listing 12.1
Our first HtmlUnit example
[...]
public class JavadocPageTest {
@Test
public void testClassNav() throws IOException {
WebClient webClient = new WebClient();
HtmlPage mainPage = (HtmlPage) webClient.getPage(
" http://htmlunit.sourceforge.net/apidocs/index.html");
HtmlPage packagePage = (HtmlPage) mainPage.getFrameByName(
"packageFrame").getEnclosedPage();
HtmlPage bVerPage = packagePage.getAnchorByHref(
"com/gargoylesoftware/htmlunit/BrowserVersion.html").click();
HtmlParagraph p = (HtmlParagraph) bVerPage.getElementsByTagName(
"p").item(0);
Assert.assertTrue("Unexpected text", p.asText().startsWith(
"Objects of this class represent one specific version of a given"));
webClient.closeAllWindows();
}
}
Let's step through the example. We always start by creating an HtmlUnit web client
b , which gives us an Internet Explorer 7 web client by default. We get to the home
page from the web client C and then to the list of classes on the page in the bottom-
left frame D . Next, we get the link for the class we're interested in and click it as a
user would E . This gives us a new page for the link we clicked, which we then query
for the first paragraph element F . Finally, we check that the paragraph starts with the
text we expect should be there G and release resources H .
This example covers the basics: getting a web page, navigating the HTML object
model, and asserting results. You'll notice a lack of standard JU nit assertions in the
code that navigates the HTML model. If HtmlUnit doesn't find an element or encoun-
ters a problem, it will throw an exception on our behalf.
B
C
D
E
F
G
H
12.3
Writing HtmlUnit tests
When you write an HtmlUnit test, you write code that simulates the action of a user sit-
ting in front of a web browser: You get a web page, enter data, read text, and click but-
tons and links. Instead of manually manipulating the browser, you programmatically
control an emulated browser. At each step, you can query the HTML object model and
assert that values are what you expect. The framework will throw exceptions if it
encounters a problem, which allows your test cases to avoid checking for these errors,
thereby reducing clutter.
12.3.1
HTML assertions
As you're familiar with by now, JU nit provides a class called Assert to allow tests to fail
when they detect an error condition. Assert is the bread and butter of any unit test.
HtmlUnit provides a class in the same spirit called WebAssert , which contains
standard assertions for HTML like assertElementPresent , assertLinkPresent , and
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search