In selenium webdriver i want to use if/else condition with java. Each steps need to be checked and need to execute one by one. For example
Log.info("Clicking on Reports link");
WebElement menuHoverLink = driver.findElement(By.id("reports"));
actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
In this code, i need to check the id once it present it need to perform the action else it need to skip the test case not to be failed.
if(driver.findElement(By.id("reports").size()!=0){
WebElement menuHoverLink = driver.findElement(By.id("reports"));
actions.moveToElement(menuHoverLink).perform();
}
else{
system.out.println("element not present -- so it entered the else loop");
}
use this one -- if the element is not persent also testcase doesnt fail
Option #1:
WebElement menuHoverLink = null;
try
{
menuHoverLink = driver.findElement(By.id("reports"));
}
catch(Exception e)
{
}
if (menuHoverLink != null)
{
actions.moveToElement(menuHoverLink).perform();
Thread.sleep(6000);
}
Option #2:
List<WebElement> menuHoverLinks = driver.findElements(By.id("reports"));
if (menuHoverLinks.size() > 0)
{
actions.moveToElement(menuHoverLinks.get(0)).perform();
Thread.sleep(6000);
}
Keep in mind that Thread.sleep
by itself may also throw an exception, so you should either catch it inside the method, or add throws Exception
at the end of the method's declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With