Reputation: 93
I wonder if someone could help me with an issue I'm having trying to work out and If statement in Java for Webdriver.
When logging into the app I am testing it is possible to be taken to a security questions page before the main page (if a new user etc). What I would like the code in my test to do is if presented with the security questions page fill it in and move on, if not check you are on the main page.
I was able to do this in Selenium RC using
if (selenium.isTextPresent("User Account Credentials Update")) {
selenium.type("//input[@id='securityQuestion']", "A");
selenium.type("//input[@id='securityAnswer']", "A");
selenium.type("//input[@id='emailAddress']", "[email protected]");
selenium.click("update");
selenium.waitForPageToLoad("30000");
}
assertTrue(selenium.isTextPresent("MainPage"));
Playing around with Webdriver I am using:
if(driver.findElement(By.id("securityQuestion")) != 0) {
driver.findElement(By.id("securityQuestion")).sendKeys("A");
driver.findElement(By.id("securityAnswer")).sendKeys("A");
driver.findElement(By.id("emailAddress")).sendKeys("[email protected]");
driver.findElement(By.id("update")).click();
Assert.assertTrue("Main Page is not Showing",
driver.getPageSource().contains("MainPage"));
The Problem with this is is that it always chucks an exception if the Security screen is not displayed. How do I need to set the code so that it ignores the security page stuff if that page is not presented? Thank you for any help :-)
Upvotes: 3
Views: 1923
Reputation: 2971
I usually just wrap it into a method:
public boolean elementExists(By selector)
{
try
{
driver.findElement(selector)
return true;
}
catch(NoSuchElementException e)
{
return false;
}
}
Upvotes: 0
Reputation: 473873
There is actually nothing wrong in an exception being thrown as long as you catch/handle it.
In other words, I'd follow the EAFP approach here:
try {
driver.findElement(By.id("securityQuestion"));
// ...
} catch (NoSuchElementException e) {
// handle exception, may be at least log in your case
}
Upvotes: 2
Reputation: 409
You can use driver.findElements
as a way to check that a specific element is present without having exceptions thrown. This works because it will return a list of size 0 of WebElements
if no element is found. At the moment, if Selenium
tries to find an element using findElement
and the element doesn't exist, it will throw a NoSuchElementException
This means you can replace:
if (driver.findElement(By.id("securityQuestion")) != 0)
with this:
if (driver.findElements(By.id("securityQuestion")).size() != 0)
Upvotes: 2