Selenium:如何让web驱动程序在执行另一个测试之前等待页面刷新

问题描述 投票:30回答:3

我在TestNG中使用Selenium web Driver编写测试用例,我有一个场景,我按顺序运行多个测试(参见下文)

@Test(priority =1)
public void Test1(){
}
@Test(priority =2)
public void Test2(){ 
}

两个测试都是AJAX调用,其中打开一个对话框,执行测试,然后关闭对话框,然后在页面顶部显示一条通知消息,并在每次成功测试后刷新页面。

问题是:Test2不等待页面刷新/重新加载。假设当Test1成功完成时,Test2将在页面刷新之前启动(即打开对话框,执行场景等)。同时页面刷新(在成功执行Test1后必然会发生)。现在,由于页面刷新,由于Test2打开的对话框不再存在,然后Test2失败。

(另外,我不知道刷新页面需要多长时间。因此,我不想在执行Test2之前使用Thread.sleep(xxxx))

另外,我不认为

driver.navigate().refresh()

将它放在Test2之前将解决我的问题,因为在这种情况下我的页面将刷新两次。问题是通过代码进行刷新(不确定因为可能需要1秒或3秒或5秒)

java selenium selenium-webdriver
3个回答
22
投票

如果你正在等待元素出现

在selenium rc我们曾经使用selenium.WaitForCondition("selenium.isElementPresent(\"fContent\")", "desiredTimeoutInMilisec")做到这一点

在Web驱动程序中,U可以使用它实现相同的功能

WebDriverWait myWait = new WebDriverWait(webDriver, 45);
ExpectedCondition<Boolean> conditionToCheck = new ExpectedCondition<Boolean>()
{
    @Override
    public Boolean apply(WebDriver input) {
        return (input.findElements(By.id("fContent")).size() > 0);
    }
};
myWait.until(conditionToCheck);

这样,您可以在执行test2之前等待元素出现。

更新 :

如果您正在等待页面加载,那么在Web驱动程序中,您可以使用以下代码:

public void waitForPageLoaded(WebDriver driver)
{
    ExpectedCondition<Boolean> expectation = new
ExpectedCondition<Boolean>() 
    {
        public Boolean apply(WebDriver driver)
        {
            return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
        }
    };
    Wait<WebDriver> wait = new WebDriverWait(driver,30);
    try
    {
        wait.until(expectation);
    }
    catch(Throwable error)
    {
        assertFalse("Timeout waiting for Page Load Request to complete.",true);
    }
}

16
投票

Here是C#.Net中WaitForPageLoad实现的更好和测试版本

public void WaitForPageLoad(int maxWaitTimeInSeconds) {
    string state = string.Empty;
    try {
        WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(maxWaitTimeInSeconds));

        //Checks every 500 ms whether predicate returns true if returns exit otherwise keep trying till it returns ture
        wait.Until(d = > {

            try {
                state = ((IJavaScriptExecutor) _driver).ExecuteScript(@"return document.readyState").ToString();
            } catch (InvalidOperationException) {
                //Ignore
            } catch (NoSuchWindowException) {
                //when popup is closed, switch to last windows
                _driver.SwitchTo().Window(_driver.WindowHandles.Last());
            }
            //In IE7 there are chances we may get state as loaded instead of complete
            return (state.Equals("complete", StringComparison.InvariantCultureIgnoreCase) || state.Equals("loaded", StringComparison.InvariantCultureIgnoreCase));

        });
    } catch (TimeoutException) {
        //sometimes Page remains in Interactive mode and never becomes Complete, then we can still try to access the controls
        if (!state.Equals("interactive", StringComparison.InvariantCultureIgnoreCase))
            throw;
    } catch (NullReferenceException) {
        //sometimes Page remains in Interactive mode and never becomes Complete, then we can still try to access the controls
        if (!state.Equals("interactive", StringComparison.InvariantCultureIgnoreCase))
            throw;
    } catch (WebDriverException) {
        if (_driver.WindowHandles.Count == 1) {
            _driver.SwitchTo().Window(_driver.WindowHandles[0]);
        }
        state = ((IJavaScriptExecutor) _driver).ExecuteScript(@"return document.readyState").ToString();
        if (!(state.Equals("complete", StringComparison.InvariantCultureIgnoreCase) || state.Equals("loaded", StringComparison.InvariantCultureIgnoreCase)))
            throw;
    }
}

0
投票

如果您可以触发URL更改,这将起作用:

WebDriverWait wait = new WebDriverWait(yourDriver, TimeSpan.FromSeconds(5));
wait.Until(ExpectedConditions.UrlContains("/url-fragment"));
© www.soinside.com 2019 - 2024. All rights reserved.