Wednesday 21 May 2014

Alert handling in Selenium WebDriver

try {
        Alert alert = webDriver.switchTo().alert();

        // check if alert exists
        // TODO find better way
        alert.getText();

        // alert handling
        log().info("Alert detected: {}" + alert.getText());
        alert.accept();
    } catch (Exception e) {
    }

The problem is that if there is no alert on the current state of the web page, it waits for a specific amount of time until the timeout is reached, then throws an exception and therefore the performance is really bad.
 public void checkAlert() {
    try {
        WebDriverWait wait = new WebDriverWait(driver, 2);
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        alert.accept();
    } catch (Exception e) {
        //exception handling
    }
}

No comments:

Post a Comment