Search code examples
javaseleniumwebdriverselenium-chromedriver

CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE) and handling alert still throws "unexpected alert open"


In chrome driver initiation I set, so if there is an alert by default it won't accept.

    caps.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);

So after clicking an element, even though I handled it still throws,

org.openqa.selenium.UnhandledAlertException: unexpected alert open

In past answers, some used try catch in the click on element then handle it. Is there any better way to handle it without using try catch block?

        element.click();
        Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
        Assert.assertEquals(alertText,"alert text");
        alert.accept();
        WebCommand.acceptAlert(driver);

Here is the alert, enter image description here


Solution

  • Instead of ignoring the unexpected alert with

    caps.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
    

    Try setting the capability to accept the alert with

    opts.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);