Java Reference
In-Depth Information
HtmlUnit tip
Create predictable tests by synchronizing Ajax calls. To do so, set the web client's
Ajax controller to an instance of NicelyResynchronizingAjaxController :
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
If you want finer-grained control over the behavior of tests, the framework provides
experimental 9 API s to wait for various JavaScript tasks to complete. The method wait-
ForBackgroundJavaScript waits for all background JavaScript tasks to complete exe-
cution, defined as tasks scheduled for execution via window.setTimeout , window.
setInterval , and asynchronous XMLHttpRequest . For example, you call waitFor-
BackgroundJavaScript after an action invokes a script with a timeout in milliseconds:
HtmlPage newPage = button.click();
int jobs = this.webClient.waitForBackgroundJavaScript(1000);
The return value is the number of jobs still executing or scheduled for execution. If
you have an idea of when your background JavaScript is supposed to start executing,
but you're not necessarily sure how long it will take to execute, use the method
waitForBackgroundJavaScriptStartingBefore . You should use the wait methods
instead of the methods internal to HtmlUnit provided by JavaScriptJobManager .
You've now seen how to create functional tests with Selenium and HtmlUnit.
Although this can prove that an application works from the perspective of a client, it
doesn't assert the quality of the underlying building blocks. It's now time to dive
deeper into testing by dealing with testing these building blocks: JavaScript and server
services. We start with JavaScript.
13.4
JavaScript testing
Here, you face the same choice you had between HtmlUnit and Selenium: do you
want to emulate a browser or drive a live browser? We look next at two JavaScript
testing frameworks, RhinoUnit and JsUnit. RhinoUnit is like HtmlUnit, a 100 per-
cent Java solution, and JsUnit is akin to Selenium in that it drives local or remote
web browsers. To wrap up JavaScript testing, we use JSL int to check our code against
best practices.
13.4.1
JavaScript testing with RhinoUnit
RhinoUnit allows you to run JavaScript unit tests from Ant. You write unit tests in
JavaScript and invoke them from Ant with the help of the Java Scripting Framework
and the Mozilla Rhino JavaScript engine included in Java 6. If you're on an older ver-
sion of Java, you'll need the Apache Bean Scripting Framework 10 ( BSF ) and the
Mozilla Rhino JavaScript engine as documented in appendix E, “Installing software.”
9
HtmlUnit 2.5 Javadoc warns that these APIs may change behavior or may not exist in future versions.
10
http://jakarta.apache.org/bsf/
 
 
 
 
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search