Java Reference
In-Depth Information
13.3.2
Functional testing with HtmlUnit
We return now to testing with HtmlUnit, which we document in chapter 12. Though
the HtmlUnit API is more verbose than that of Selenium, you write tests entirely in
Java. Listing 13.3 tests the form with HtmlUnit.
Listing 13.3
Testing the same form with HtmlUnit
public class AjaxFormTest {
private static final String EXPECTED_MSG = "Hello World";
private static final String TEST_URL =
" http://localhost/webapp/formtest.html";
@Test
public void testAjaxForm() throws IOException {
WebClient webClient = new WebClient();
try {
webClient.setAjaxController(new
NicelyResynchronizingAjaxController());
HtmlPage page = (HtmlPage) webClient.getPage(TEST_URL);
HtmlButtonInput button = (HtmlButtonInput)
page.getFirstByXPath("/html/body/form/input[1]");
HtmlPage newPage = button.click();
HtmlInput reply = (HtmlInput)
newPage.getFirstByXPath("/html/body/form/input[2]");
Assert.assertTrue(EXPECTED_MSG.equals(reply.asText()));
} finally {
webClient.closeAllWindows();
}
}
}
Let's walk through this example. As usual, we start by creating an HtmlUnit web client
and getting the application's start page C . We get our button, we click it, and the
result is a new page D . From this page, we get the entry field that was updated
through the DOM by the XHR call and assert that the contents are what we expect E .
The general pattern with HtmlUnit is to get a page, find the element, click it, and
check the resulting page contents.
Because the test thread can finish before HtmlUnit reads the Ajax response from
the server, you must synchronize the test code with the response to guarantee predict-
able results from run to run. Although a simple approach is to sleep the thread for a
while, HtmlUnit provides API s to guarantee that Ajax tests are synchronous and pre-
dictable. This example illustrates this with the call to setAjaxController b .
The setAjaxController method and the NicelyResynchronizingAjaxController
class work together to turn asynchronous Ajax calls into synchronous Ajax calls.
The class NicelyResynchronizingAjaxController is the only subclass of the Ajax-
Controller class delivered with HtmlUnit. By default, a web client initializes itself with
an instance of AjaxController, which leaves Ajax calls asynchronous.
B
C
D
E
 
 
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search