Java Reference
In-Depth Information
though Selenium defines SeleniumException and SeleniumCommandTimedOut-
Exception as unchecked exceptions, some API s also throw RuntimeException .
Let's now look at various examples of using the API and navigating an application.
12.8.6
Testing forms with Selenium
The API doesn't provide explicit support for forms; instead, you work with forms as
you would any other elements, calling API s for typing, clicking, and pressing keys.
The following example recasts the HtmlUnit example from the “Testing forms
with HtmlUnit” section to the Selenium API . To remind you, in the HtmlUnit section,
we created a simple page to display a form with an input field and a Submit button.
We included form validation via JavaScript alerts in the example as a second path to
test, as described in the section “Testing JavaScript alerts.”
We test normal user interaction with the form as follows:
@Test
public void testForm() throws IOException {
selenium.open("file:///C:/path/to/src/main/webapp/formtest.html");
selenium.type("id=in_text", "typing...");
selenium.click("id=submit");
SeleneseTestCase.assertEquals("Result", selenium.getTitle());
}
Let's step through the example. We open the form page, type in a value, and click the
Submit button to go to the next page. Finally, we make sure we land on the right page.
If at any step Selenium can't find an object, the framework throws an exception
and your test automatically fails. This allows you to focus on the test and let the frame-
work handle failing your test if the page or form is not as expected.
12.8.7
Testing JavaScript alerts
A test can check to see whether a JavaScript alert has 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 following test loads our form page and checks that the browser raised the alert
when the error condition occurred. The key method is getAlert , which returns the
most recent JavaScript alert message. Calling getAlert has the same effect as clicking
OK in the dialog box.
@Test
public void testFormAlert() throws IOException {
selenium.open("file:///C:/path//to/src/main/webapp/formtest.html");
String title = selenium.getTitle();
selenium.click("id=submit");
SeleneseTestCase.assertEquals("Please enter a value.",
selenium.getAlert());
SeleneseTestCase.assertEquals(title, selenium.getTitle());
}
B
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search