I came across the problem described in Checking If alert exists before switching to it. I find horrible to capture a NullPointerException. Has anyone solved this problem more elegantly?
My current solution uses a wait that captures the NPE. The client code just have to invoke waitForAlert(driver, TIMEOUT):
/**
* If no alert is popped-up within <tt>seconds</tt>, this method will throw
* a non-specified <tt>Throwable</tt>.
*
* @return alert handler
* @see org.openqa.selenium.support.ui.Wait.until(com.google.common.base.Function)
*/
public static Alert waitForAlert(WebDriver driver, int seconds) {
Wait<WebDriver> wait = new WebDriverWait(driver, seconds);
return wait.until(new AlertAvailable());
}
private static class AlertAvailable implements ExpectedCondition<Alert> {
private Alert alert = null;
@Override
public Alert apply(WebDriver driver) {
Alert result = null;
if (null == alert) {
alert = driver.switchTo().alert();
}
try {
alert.getText();
result = alert;
} catch (NullPointerException npe) {
// Getting around https://groups.google.com/d/topic/selenium-users/-X2XEQU7hl4/discussion
}
return result;
}
}
Based upon @Joe Coder answer, a simplified version of this wait would be:
I have written a short test to proof the concept:
In this code, in the
untiltheMyObject.get()is invoked four times. The third time, it throws an ignored exception, but the last one throws a not-ignored exception, interrupting the wait.The output (simplified for readability):
Note that as the
RuntimeExceptionis not ignored, the “Returned from wait” log is not printed.