Java Reference
In-Depth Information
C LICK NAVIGATION
The click and dblClick methods conveniently navigate through a link or any click-
able user interface element. For example, continuing from the previous example, we
enter a web query and click the Search button:
HtmlForm form = page.getFormByName("f");
HtmlTextInput queryText = (HtmlTextInput) form.getInputByName("q");
queryText.setValueAttribute("Manning Publications Co.");
HtmlSubmitInput searchButton = (HtmlSubmitInput) form.getInputByName("btnG");
HtmlPage resultPage = (HtmlPage) searchButton.click();
You can call the click and dblClick methods on all classes descending from Html-
Element . Click methods simulate clicking an element (remember, HtmlUnit is an
emulator) and return the page in the window that has the focus after the element has
been clicked.
The HTML 4.01 specification 9 defines clickable HTML elements. HtmlElement is
the base class for all HTML elements except frame and iframe.
See the HtmlElement Javadoc 10 or select HtmlElement in Eclipse and hit F4 to dis-
play the class hierarchy.
K EYBOARD NAVIGATION
To simulate the user hitting the Enter key instead of clicking the Search button,
replace getting and clicking the search button with the following:
HtmlPage resultPage = (HtmlPage) queryText.type('\n');
You can code the Enter key with the '\n' character. You can also simulate the user
tabbing around the page with the HtmlPage methods tabToNextElement and tabTo-
PreviousElement . Hitting the Enter key or any key may not be enough or the right
process to test. You can set the focus to any element with the HtmlPage method set-
FocusedElement . Be aware that this will trigger any onfocus and onblur event han-
dlers. Let's now put these concepts together with another example and test forms.
12.3.12 Testing forms with HtmlUnit
HTML form support is built into the HtmlPage API , where form elements can be
accessed with getForms (returns List<HtmlForm> ) to get all form elements and get-
FormByName to get the first HtmlForm with a given name. You can call one of the Html-
Form getInput methods to get HTML input elements and then simulate user input
with setValueAttribute .
The following example focuses on the HtmlUnit mechanics of driving a form.
First, we create a simple page to display a form with an input field and Submit button.
We include form validation via JavaScript alerts in listing 12.5 as a second path to test.
The section “Testing JavaScript alerts” describes this in more detail.
9
http://www.w3.org/TR/html401/
10
http://htmlunit.sourceforge.net/apidocs/com/gargoylesoftware/htmlunit/html/HtmlElement.html
 
 
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search