Selenium-Java等待页面加载在测试脚本中失败
我使用JAVA和一些Selenium脚本在EclipseIDE中创建测试用例 我的问题是,有时候,连续运行测试用例会在selenium.waitForPageToLoad(“30000”)方法中产生错误/失败的测试。我提出了一个解决方案,该方法将循环,直到满足特定的条件,所以我使用了这段代码。但这不起作用 发生的情况如下:运行Junit Test>@Test1,2,3..n>页面未加载@Test n>执行下一行代码>在@Test n>中失败的测试,因为页面未加载,所以无法执行下一个脚本(页面中缺少必需的元素,因为它未加载) 这就是应该发生的情况:运行Junit Test>@Test1,2,3..n>页面不加载@Test n>等待页面加载,直到满足特定条件(例如,页面中已存在元素X)>执行下一行代码>在@Test n中通过测试 我需要一个解决方案,等待页面加载,直到出现下一行脚本所需的元素 这个代码不起作用。我非常需要你的帮助。谢谢Selenium-Java等待页面加载在测试脚本中失败,java,unit-testing,selenium,selenium-rc,Java,Unit Testing,Selenium,Selenium Rc,我使用JAVA和一些Selenium脚本在EclipseIDE中创建测试用例 我的问题是,有时候,连续运行测试用例会在selenium.waitForPageToLoad(“30000”)方法中产生错误/失败的测试。我提出了一个解决方案,该方法将循环,直到满足特定的条件,所以我使用了这段代码。但这不起作用 发生的情况如下:运行Junit Test>@Test1,2,3..n>页面未加载@Test n>执行下一行代码>在@Test n>中失败的测试,因为页面未加载,所以无法执行下一个脚本(页面中缺
//Wait for Page to Load until Expected Element is not Present
public void waitForPageToLoadElement(final String isElementPresent){
boolean elementBoolean;
do{
selenium.waitForPageToLoad("30000");
elementBoolean = selenium.isElementPresent(isElementPresent);
if (elementBoolean==false){
try{Thread.sleep(3000);}
catch (Exception e) {
//catch
}}
}
while(elementBoolean==false);
}
//Wait for Page to Load until Expected Text is not Present
public void waitForPageToLoadText(String isTextPresent){
boolean elementBoolean;
do{
selenium.waitForPageToLoad("30000");
elementBoolean = selenium.isTextPresent(isTextPresent);
if (elementBoolean==false){
try{Thread.sleep(3000);}
catch (Exception e) {
//catch
}}
}
while(elementBoolean==false);
}
//Opens url until Expected Element is not Present
public void openUrl(String url){
boolean userNameBoolean, passwordBoolean;
do {
selenium.open(url);
userNameBoolean = selenium.isElementPresent("id=loginForm:username");
passwordBoolean = selenium.isElementPresent("id=loginForm:password");
if (userNameBoolean==false && passwordBoolean==false){
try{Thread.sleep(3000);}
catch (Exception e) {
//catch
}}
}while (userNameBoolean==false && passwordBoolean==false);
}
这种逻辑可能对您有所帮助
public static void waitforElement(Selenium selenium,String element)
{
try
{
int second;
for (second = 0; ; second++)
{
if (selenium.isElementPresent(element))
{
break;
}
if (second >= 20)
{
break;
}
Thread.sleep(1000);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
在对任何元素执行任何操作之前,只需为该元素调用此方法,以便在未找到该元素时,它将等待该元素,直到达到超时(即20秒)
示例
waitforElement(selenium,"id=loginForm:username");
selenium.type("id=loginForm:username","username");
waitforElement(selenium,"id=loginForm:password");
selenium.type("id=loginForm:password","password");
selenium.click("submit");
我认为如果找不到元素,您的案例将与上面的代码进行无休止的循环。元素是否出现在页面上,但未找到?它是针对特定元件还是随机发生的?如果未加载,则所有元件都不存在。这是随机发生的。我需要另一个代码,该代码将等待直到满足条件not waitForPageToLoad(毫秒)方法。参数Selenium Selenium?用于检查该方法中的Selenium.isElementPresent(元素)的用途是什么。