首页 > 解决方案 > Selenium: Alert fails to execute before driver closes

问题描述

I have a code like this:

public class classTest {
    WebDriver webDriver;
    WebDriverWait wait;

    ExpectedCondition<Boolean> pageLoadCondition = new
            ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver driver) {
                    return ((JavascriptExecutor) driver)
                            .executeScript("return document.readyState")
                            .equals("complete");
                }
            };

    @BeforeEach
    public void init() {
        webDriver = new FirefoxDriver();
        wait = new WebDriverWait(webDriver, 10);
    }

    @AfterEach
    public void quit() {
        webDriver.quit();
    }

    @Test
    public void Test1() {
            ...
    }

    @Nested
    class classTest2 {
        @BeforeEach
        public void create() {
            ...
        }

        @AfterEach
        public void closeAlert() {
            webDriver.get("https://...");

            ...

            Alert alert = wait.until(ExpectedConditions.alertIsPresent());
            webDriver.switchTo().alert().accept();
        }

        @Test
        public void Test2() {
            ...
        }
   ...           

When Test2() completes, the closeAlert() method is executed.

An alert appears on the page, but accept() fires 50% of the time. My guess is that it does not have time to fire, because the quit() method is immediately executed, which closes the browser.

I've triedwait.until(pageLoadCondition); after alert, but that doesn't help.

How do I wait for the alert confirmation to complete?

标签: seleniumselenium-webdriverjunitwebdriverbrowser-automation

解决方案


您可以等待在网页上显示/等实际的 WebElement。

如果您没有特定元素,则可以使用几毫秒的Thread.sleep.
可能不是理想的解决方案,但只要您只需要等待,别无其他,它应该可以解决问题。


推荐阅读