vamc
vamc

Reputation: 125

if/else statement fail

I'm using if/else statements as below, but the script fails in Selenium WebDriver. Here, for one test case the if statement works but, for another test case, the else one doesn't.

if (driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--top")).isDisplayed()){
        driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--top")).click();
    }
    else
    {
        driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--bottom")).click();
    }

Upvotes: 0

Views: 1142

Answers (3)

Siva
Siva

Reputation: 1149

Im not good at Java, so im putting the steps. Give try. 1. First Find elements seperately. 2. Now check if 'top' is not null and then check for is displayed and can continue further .Pseudo code below

IWebElement top= driver.findelement( put you locator top here )
 IWebElement bottom = driver.findelement( put you bottom here)
 if(top!=null)
 {
  if(top.IsDisplayed)
  {
   top.click()
  }
}
else
{
  if(bottom!=null)
  {
    bottom.click()
  }
}

Upvotes: 1

Leon Barkan
Leon Barkan

Reputation: 2703

        try
        {
        if (driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--top")).isDisplayed()==true)
            driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--top")).click();
        }
        catch(Exception ex)
        {
            driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--bottom")).click();
        }

Upvotes: 1

murali selenium
murali selenium

Reputation: 3927

we need to click on element "div.Tooltip__body.Tooltip__body--top" if it is displayed. if not then need to click on "div.Tooltip__body.Tooltip__body--bottom"

If we use .isDisplayed to check element displayed or not, in any case element is not there, it will throw exception. that's why we need to handle this exception by using try/catch.

    try{

        //if element is displayed, then click it
         if (driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--top")).isDisplayed()==true){
             driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--top")).click();
    }

    }catch(Exception e){

        //exception occurred as element (top) is not available.
        //so i need to click on bottom
          driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--bottom")).click();
         //if required we can collect exception : e.getMessage()

    }

Thanks

Upvotes: 1

Related Questions