gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:06:19 25 4
gpt4 key购买 nike

我正在 TestNG 中使用 Selenium Web 驱动程序编写测试用例,并且我有一个场景是我正在按顺序运行多个测试(请参阅下文)

@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 秒)

最佳答案

如果您正在等待元素出现,那么

在 selenium rc 中,我们曾经使用 selenium.WaitForCondition("selenium.isElementPresent(\"fContent\")", "desiredTimeoutInMilisec")

在 web 驱动中你可以使用这个实现同样的事情

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);
}
}

关于java - Selenium:如何使 Web 驱动程序在执行另一个测试之前等待页面刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13244225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com