A simple example of Selenium WebDriver implicit exception handling can be described as follows:
- Define an element on a page
- Create a method to retrieve the text from the element on the page
- In the signature of the method, add throws Exception
- Do not handle a specific exception like ElementNotFoundException:
// create a method to retrieve the text from an element on a page
@FindBy(id="submit")
protected M submit;
public String getText(WebElement element) throws Exception {
return element.getText();
}
// use the method
LoginPO.getText(submit);
Now, when using an assertion method, TestNG will implicitly throw an exception if the condition is not met:
- Define an element on a page
- Create a method to verify the text of the element on a page
- Cast the expected and actual text to the TestNG's assertEquals method
- TestNG will throw an AssertionError
- TestNG engages the difference viewer to compare the result if it fails:
// create a method to verify the text from an element on a page
@FindBy(id="submit")
protected M submit;
public void verifyText(WebElement element,
String expText)
throws AssertionError {
assertEquals(element.getText(),
expText,
"Verify Submit Button Text");
}
// use the method
LoginPO.verifyText(submit, "Sign Inx");
// throws AssertionError
java.lang.AssertionError: Verify Text Label expected [ Sign Inx] but found [ Sign In]
Expected : Sign Inx
Actual : Sign In
<Click to see difference>