0

我使用 JAVA 和一些 Selenium 脚本在 Eclipse IDE 中创建测试用例。

我的问题是,有时,测试用例的连续运行会在 selenium.waitForPageToLoad("30000") 方法中产生错误/失败的测试。我提出了一个解决方案,该方法将循环直到满足特定条件,所以我来到了这段代码。但这不起作用。

会发生这种情况:运行 Junit Test > @Test1,2,3..n > 页面未加载 @Test n > 执行下一行代码 > 在 @Test n 中测试失败 > 因为页面未加载,因此无法完成下一个脚本(页面中缺少必需的元素,因为它没有加载)。

这应该发生的事情:运行 Junit Test > @Test1,2,3..n > 页面不加载 @Test n > 等待页面加载,直到满足特定条件(例如元素 X 已经存在于页面中) > 执行下一行代码 > 在@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);

}
4

1 回答 1

0

这种类型的逻辑可能对你有帮助

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");
于 2013-02-07T13:35:47.090 回答