Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use if/else condition in selenium webdriver?

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.

like image 390
testing Avatar asked Feb 14 '23 01:02

testing


2 Answers

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

like image 169
Dilip Kumar Avatar answered Feb 17 '23 12:02

Dilip Kumar


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.

like image 21
barak manos Avatar answered Feb 17 '23 14:02

barak manos