Java Reference
In-Depth Information
form object, get the Submit button, and click it
D
. This invokes the JavaScript,
which calls the alert. Clicking the button returns a page object, which we use to
check that the page has not changed by comparing current and previous page titles.
We also check that the page has not changed by comparing current and previous
page objects. Note that this comparison uses
Object
equals
, so we're really asking
whether the page objects are identical. This might not be a great test if a future ver-
sion of the framework implements
equals
in an unexpected manner. Finally, we get
the list of alert messages that were raised
E
, create a list of expected alert messages,
and compare the expected and actual lists.
JUnit tip
When using any assertion that use the
equals
methods, make sure you under-
stand the semantics of the
equals
implementation of the objects you're compar-
ing. The default implementation of
equals
in
Object
returns
true
if the objects
are the same.
Next, listing 12.9 rewrites the original form test to make sure that normal operation
raises no alerts.
Listing 12.9
Asserting no alerts under normal operation
@Test
public void
testFormNoAlert()
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");
HtmlTextInput input = (HtmlTextInput) form.getInputByName("in_text");
input.setValueAttribute("typing...");
HtmlSubmitInput submitButton = (HtmlSubmitInput)
form.getInputByName("submit");
HtmlPage resultPage = (HtmlPage) submitButton.click();
WebAssert.assertTitleEquals(resultPage, "Result");
assertTrue("No alerts expected",
alertHandler.getCollectedAlerts().isEmpty());
webClient.closeAllWindows();
}
The differences with the original test are that at the beginning of the test
b
we
install a
CollectingAlertHandler
in the web client, we simulate a user entering a
value
C
, and at the end of the test we check that the alert handler's list of mes-
sages is empty
D
.
To customize the alert behavior, you need to implement your own
AlertHandler
.
Listing 12.10 will cause your test to fail when a script raises the first alert.
B
C
D