Java Reference
In-Depth Information
HtmlPage page3 = webClient.getPage(page3Url);
Assert.assertEquals("Hello 3!", page3.getTitleText());
webClient.closeAllWindows();
}
This example installs three pages b in the mock connection and tests getting each
page C and verifying each page title D .
Common pitfall
Don't forget the trailing slash (/) in the URL; “ http://Page1/” w ill work but “ http://
Page1” wo n't be found in the mock connection and will therefore throw an exception.
12.3.5
Navigating the object model
HtmlUnit provides an object model that parallels the HTML object model. You'll use it
to navigate through your application's web pages. Let's explore it now.
To get to an HTML page, you always start with a WebClient and call getPage:
WebClient webClient = new WebClient();
HtmlPage page = (HtmlPage) webClient.getPage(" http://www.google.com");
HtmlPage is HtmlUnit's model of an HTML page returned from a server. Once you
have a page, you access its contents in one of three ways:
Call methods reflecting specific HTML concepts like forms, anchors, and frames.
Call methods that address HTML elements by references using names and ID s.
Call methods using XP ath, a web standard for addressing XML document nodes.
Let's now look at each technique.
12.3.6
Accessing elements by specific element type
The HtmlPage API provides methods reflecting the HTML element model: for anchors,
getAnchorByName , getAnchors , and others; for a body, getBody ; for forms, getForm-
ByName , getForms ; for frames, getFrameByName , getFrames ; for meta tags, getMeta-
Tags . We explore specifically how to work with form and frame elements in the
following sections.
12.3.7
Accessing elements by name versus index
This discussion applies to all methods that return a List : getAnchors , getForms , and
getFrames . You should consider the implication of addressing these lists with indexes.
For example, consider the following snippet:
HtmlForm form = page.getForms().get(0);
The index access creates an assumption in your test that the HTML form you want to
test will always be the first form in the list. If the page changes and the search form
changes position, your test will fail, even though the page's functionality may not have
 
 
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search