从Selenium 1到Selenium 2迁移isElementPresent()时如何避免超时?

时间:2012-09-21 06:35:38

标签: java selenium migration webdriver integration-testing

我正在尝试将Java代码从Selenium 1(RC)迁移到Selenium 2(WebDriver),看起来像这样:

1:  selenium.click(someButton);
2:  selenium.waitForPageToLoad();
3:  if (!selenium.isElementPresent(errorMessageElement)) {
4:     Assert.fail("Test failed! No error msg should be displayed on page.");
5:  }

关键部分是第3行,我试图根据Rostislav Matl的建议翻译成Selenium 2:

3:  if (!driver.findElements(By.xpath(errorMessageElement)).size() > 0) {

不幸的是,WebDriver等待整个超时(在我的情况下为60秒)来检测元素是否确实存在。虽然这有效,但它引入了太多的时间开销......

在Selenium 2中是否有时间有效地检查当前在Web浏览器中显示的HTML页面上是否存在元素?

3 个答案:

答案 0 :(得分:3)

这是两部分答案

  1. 时间开销是正确的:正如您想要确保该元素确实未呈现一样。也就是说,考虑页面渲染时间,AJAX元素等。我知道错误消息会随着页面加载一起显示,但是如果你想要检查ajax元素的存在(或不存在),这些元素会以几毫秒的延迟显示,那么超时非常有用。

  2. 黑客以减少等待开销:您仍然可以创建一种暂时重置隐藏等待时间的方法

  3. public boolean isElementNotPresent(By by) {
        boolean flag = true;
        driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
        if (!driver.findElements(by).size() > 0) {
            flag = false;
        } 
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        return flag;
    }
    

    并调用此方法来检查缺席,例如第3行和第4行将是

    if (!isElementNotPresent(By.xpath(xpathoferrorelement))) {
        Assert.fail("Test failed! No error msg should be displayed on page.");
    }
    

答案 1 :(得分:1)

尝试使用FluentWait Class,可以轻松配置您想要使用的条件: http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html

答案 2 :(得分:0)

当页面已经呈现时,我经常使用的几种方法(用于验证存在或不存在)。 方法1:

input.findElements(By.xpath("//xpath")).size() > 0

方法2:

driver.findElement(By.cssSelector(propertyKeysLoader(key))).isDisplayed()

方法3:

public bool IsElementPresent(By selector)
{
    return driver.FindElements(selector).Any();
}

如果你想要渲染元素(如果你的页面上没有所有的AJAX)那么你最好像Arek所提到的那样使用流畅的等待。

 public WebElement fluentWait(final By locator){
        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(30, TimeUnit.SECONDS)
                .pollingEvery(5, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class);

        WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                        return driver.findElement(locator);
                }
                }
);
                           return  foo;              }     ;

在字符串.pollingEvery(5, TimeUnit.SECONDS)中,您可以设置任何迭代超时。很舒服。 希望这能以某种方式帮助你)