Java Reference
In-Depth Information
By now, you should have the hang of using the API , so let's move on to JavaScript,
CSS , and other topics.
12.3.14 Testing JavaScript
HtmlUnit processes JavaScript automatically. Even when, for example, HTML is gener-
ated with Document.write() , you follow the usual pattern: call getPage , find an ele-
ment, call click on it, and check the result.
You can toggle JavaScript support on and off in a web client by calling set-
JavaScriptEnabled . HtmlUnit enables JavaScript support by default. You can also set
how a long a script is allowed to run before being terminated with setJavaScript-
Timeout and passing it a timeout in milliseconds.
To deal with JavaScript alert and confirm calls, you can provide the framework with
callbacks routines. We explore these next.
T ESTING J AVA S CRIPT ALERTS
Your tests can check which JavaScript alerts have taken place. We reuse our form
example from section 12.3.12, “Testing forms with HtmlUnit,” which includes
JavaScript validation code to alert the user of empty input values.
The test in listing 12.8 loads our form page and checks calling the alert when the
form detects an error condition. In a second example, we enhance our existing test
from section 12.3.12 to ensure that normal operation of the form doesn't raise any
alerts. Our test will install an alert handler that gathers all alerts and checks the result
after the page has been loaded. The stock class CollectingAlertHandler saves alert
messages for later inspection.
Listing 12.8
Asserting expected alerts
@Test
public void testFormAlert() throws IOException {
WebClient webClient = new WebClient();
CollectingAlertHandler alertHandler = new CollectingAlertHandler();
webClient.setAlertHandler(alertHandler);
HtmlPage page = (HtmlPage)
webClient.getPage("file:src/main/webapp/formtest.html");
HtmlForm form = page.getFormByName("validated_form");
HtmlSubmitInput submitButton = (HtmlSubmitInput)
form.getInputByName("submit");
HtmlPage resultPage = (HtmlPage) submitButton.click();
assertEquals(resultPage.getTitleText(), page.getTitleText());
assertEquals(resultPage, page);
List<String> collectedAlerts = alertHandler.getCollectedAlerts();
List<String> expectedAlerts =
Collections.singletonList("Please enter a value.");
assertEquals(expectedAlerts, collectedAlerts);
webClient.closeAllWindows();
}
Let's work through the example: We start by creating the web client and alert han-
dler b , which we install in the web client C . Next, we get the form page, get the
B
C
D
E
 
 
 
 
 
Search WWH ::




Custom Search