使用hiddenlyWait与Webdriver

时间:2011-06-20 10:32:40

标签: selenium webdriver selenium-webdriver

lib- selenium-java2.0rc2.jar和selenium-server-standalone-2.-b3.jar

简单测试:

webDriver = new FirefoxDriver();
webDriver.get("http://www.google.com");
webDriver.findElement(By.name("q")).sendKeys("Test");
webDriver.findElement(By.name("btnG")).click();

Assert.assertTrue(webDriver.findElement(By.cssSelector("ol#rso>li:nth-child(1) a"))
            .getText().equalsIgnoreCase("Test.com Web Based Testing and Certification Software v2.0")); 

断言失败,然后我在asserition之前添加了 BAD 等待声明 -

Thread.sleep(3000);
Assert.assertTrue(webDriver.findElement(By.cssSelector("ol#rso>li:nth-child(1) a"))
.getText().equalsIgnoreCase("Test.com Web Based Testing and Certification Software v2.0")); 

测试成功。 但后来遇到了隐含的等待并将其用作 -

webDriver = new FirefoxDriver();

webDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

webDriver.get("http://www.google.com");
webDriver.findElement(By.name("q")).sendKeys("Test");
webDriver.findElement(By.name("btnG")).click();
Assert.assertTrue(webDriver.findElement(By.cssSelector("ol#rso>li:nth-child(1) a"))
.getText().equalsIgnoreCase("Test.com Web Based Testing and Certification Software v2.0"));

断言再次失败,看起来像implicitlyWait()在这里没有任何影响。我绝对不想使用Thread.sleep()。可能的解决方案是什么?

1 个答案:

答案 0 :(得分:3)

您可以使用webdriverwait类来等待预期的条件成真。

     ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            //Wait until text changes
                    return webDriver.findElement(By.cssSelector("ol#rso>li:nth-child(1) a"))
                    .getText().equalsIgnoreCase("Test.com Web Based Testing and Certification Software v2.0"));
          }
        };

        Wait w = new WebDriverWait(driver, 60);
        w.until(e);

    //do asserts now
    Assert.assertTrue(...);