偶尔测试导致错误

时间:2012-10-16 09:11:00

标签: selenium webdriver selenium-webdriver

运行Selenium Webdriver测试时,我有一个非常奇怪的问题。

我的代码

driver.findElement(By.id("id")).click();
driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[starts-with(@href,'/problematic_url')]")).click();
driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);
driver.findElement(By.className("green_true")).click();

元素实际存在。我甚至可以看到有问题的网址被网络驱动程序点击,但后来没有任何反应。浏览器不会进入页面,也不会找到green_true元素。导致错误。但只是偶尔。有时测试应该运行。

谁能说出这是怎么回事?

我无法使用确切的网址,因为它们会根据所选语言而有所不同。

2 个答案:

答案 0 :(得分:0)

好。建议以下列方式修改: 而不是

driver.findElement(By.id("id")).click();
driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[starts-with(@href,'/problematic_url')]")).click();
driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);
driver.findElement(By.className("green_true")).click();

尝试使用以下内容:

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

fluentWait(By.id("id")).click();
fluentWait(By.xpath("//a[starts-with(@href,'/problematic_url')]")).click();
fluentWait(By.className("green_true")).click();

问题可能是你在与元素交互(点击等)之后在页面上获得了一些AJAX。恕我直言,我们需要使用更强大的等待机制。

一条建议:当你获得webelement或css选择器的xpath时,不要忘记在fireBug,ffox扩展中验证找到的定位器。 locators verify 问候。

答案 1 :(得分:0)

在单击动态元素时尝试使用显式等待。等到元素出现在Web浏览器上或对其应用操作。您可以使用此模式:

final FluentWait<WebDriver> wait =
            new FluentWait<WebDriver>(getDriver())
                    .withTimeout(MASK_PRESENCE_TIMEOUT, TimeUnit.SECONDS)
                    .pollingEvery(100, TimeUnit.MILLISECONDS)
                    .ignoring(NoSuchElementException.class)
                    .ignoring(StaleElementReferenceException.class)
                    .withMessage("Time out while waiting the element is loaded");

    wait.until(new Predicate<WebDriver>() {

        @Override
        public boolean apply(final WebDriver driver) {
            return ! driver.findElements(By.id("id")).isEmpty(); 
        }

    });
相关问题