Selenium WebDriver可靠的测试

我知道这个问题之前曾被问过很多次,但我仍然找不到适合我的解决方案.当我使用Selenium WebDriver运行我的测试时,大多数情况下它们会因“NoSuchElementException”而失败.我尝试使用Explicit和Implicit Waits,但似乎没有任何效果.那么,除了使用Waits之外还有其他方法可以使我的测试更可靠吗?

我正在使用selenium-java-2.31.0和FirefoxDriver.下面是我尝试使测试更可靠的一些代码示例:

public void waitAndClickElement(WebDriver driver, final By selector) {
        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(50, TimeUnit.SECONDS)
                .pollingEvery(5, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class);
        WebElement elementToClick = wait
                .until(new Function<WebDriver, WebElement>() {
                    public WebElement apply(WebDriver driver) {
                        return driver.findElement(selector);
                    }

                });
        waitForElementVisible(driver, selector);
        elementToClick.click();
         }

..还有这个:

public WebElement waitForElementPresent(WebDriver driver, final By selector){
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(70, TimeUnit.SECONDS)
            .pollingEvery(5, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);
    WebElement elementToClick = wait
            .until(new Function<WebDriver, WebElement>() {
                public WebElement apply(WebDriver driver) {
                    return driver.findElement(selector);
                }
            });
    return elementToClick;

    } 

…还有这个:

WebDriverWait wait = new WebDriverWait(driver, 50);
WebElement user_name = wait.until(visibilityOfElementLocated(By.xpath("//*@id='userName']")));

…还有这个:

driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

…最后我尝试使其更可靠的测试之一:

@Test
public void test1{
 waitAndClickElement(driver, By.xpath("//*[@id='linkLogIn']"));
        waitForElementPresent(driver, By.xpath("//*[@id='userName']")).sendKeys("name");
        waitForElementPresent(driver, By.xpath("//*[@id='inputEmail']")).sendKeys("email@gmail.com");
        waitForElementPresent(driver,By.xpath("//*[@id='resetPassword']")).click();
        assertTrue(isElementPresent(By.xpath("//*[@id='moduleMain']")));

}

谢谢!

最佳答案 尝试以下自定义方法.这对我来说可以,

public boolean waitForElementToBePresent(By by, int waitInMilliSeconds) throws Exception
    {
        WebDriver driver = getDriver();
        int wait = waitInMilliSeconds;
        int iterations  = (wait/250);
        long startmilliSec = System.currentTimeMillis();
        for (int i = 0; i < iterations; i++)
        {
            if((System.currentTimeMillis()-startmilliSec)>wait)
                return false;
            List<WebElement> elements = driver.findElements(by);
            if (elements != null && elements.size() > 0)
                return true;
            Thread.sleep(250);
        }
        return false;
    }

使用它,像,

waitForElementToBePresent(By.id("linkLogIn", 5000);
driver.findElement(By.id("linkLogIn")).click(); 
点赞