我知道这个问题以前被问过很多次,但我仍然找不到适合我的解决方案。当我大多数时候使用 Selenium WebDriver 运行测试时,它们会因“NoSuchElementException”而失败。我尝试使用显式和隐式等待,但似乎没有任何效果。那么,除了使用 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']")));
}
谢谢!