Java Reference
In-Depth Information
a great way to gather values on a page, whether or not the values are formally present
in a list-like structure like an HTML table, list, or form.
For example, this expression returns an anchor list from the Java 6 Javadoc page
for all package names:
//a[contains(@href, 'package-frame.html') and @target='packageFrame']
To s e e t h i s XP ath expression in action, go to the Java 6 Javadoc page:
client = new WebClient();
mainPage = (HtmlPage) client.getPage
(" http://java.sun.com/javase/6/docs/api/index.html");
Then go to the package list page:
HtmlPage packageListPage = (HtmlPage) mainPage.getFrameByName
("packageListFrame").getEnclosedPage();
From that page, we can gather all links that point to a Java package:
List<DomNode> anchors = (List<DomNode>) packageListPage.getByXPath
("//a[contains(@href, 'package-frame.html') and @target='packageFrame']");
Beware that there's an XP ath version 1.0 7 and 2.0 8 specification. HtmlUnit includes
the Apache Xalan XP ath implementation, which supports only 1.0. If you want to use
XP ath 2.0 features, you need to get an XP ath 2.0 engine, which usually means an XSL
2.0 engine, like Saxon. You'll also need to write some code, an advanced endeavor.
12.3.10 Test failures and exceptions
Tests check for error conditions with the JU nit Assert class and the HtmlUnit Web-
Assert class and by letting the HtmlUnit API throw unchecked exceptions. We already
covered the WebAssert class in section 12.3.1, “ HTML assertions.” For example, if you
query for a form with an invalid name by calling HtmlPage getFormByName , you'll get
the exception
com.gargoylesoftware.htmlunit.ElementNotFoundException:
elementName=[form] attributeName=[name] attributeValue=[unknown_element]
If you call WebClient getPage and the page doesn't exist, you'll get the exception
java.net.UnknownHostException: unknown_page
HtmlUnit defines exceptions like ElementNotFoundException in the package
com.gargoylesoftware.htmlunit . To verify that a method throws an expected
exception, annotate the method with the expected attribute:
@Test(expected = ElementNotFoundException.class)
Because these exceptions are all unchecked, you don't have to throw them from
your methods, but you'll need to remember to catch them if you want to examine
7
XPath 1.0: http://www.w3.org/TR/1999/REC-xpath-19991116
8
XPath 2.0: http://www.w3.org/TR/xpath20/
 
 
 
 
 
Search WWH ::




Custom Search