I know this question has been asked many times before, but I still could not find a solution that works for me. When I run tests with Selenium WebDriver in most cases, they fail with a "NoSuchElementException". I tried to use Explicit and Implicit Expectations, but nothing works. So, is there any other way besides using Waits in which I can make my tests more reliable?
I am using selenium-java-2.31.0 with FirefoxDriver. The following are sample code that I tried to make my tests more reliable:
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(); }
.. and this:
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; }
... and this:
WebDriverWait wait = new WebDriverWait(driver, 50); WebElement user_name = wait.until(visibilityOfElementLocated(By.xpath("//*@id='userName']")));
... and this:
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
... and finally, one of the tests I'm trying to make more reliable:
@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']")));
}
Thanks!