eclipseseleniumif-statementselenium-webdrivertestng-eclipse

Below If else condition is not working in my script


driver.findElement(By.id("btnSendMailCopy")).click();
Thread.sleep(3000);
if(driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).isDisplayed())
{     
    driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).click();   
    System.out.println("clicked");
}
else if(driver.findElement(By.id("VendorCardHolderName")).isDisplayed())
{  
    Select dropdown = new Select(driver.findElement(By.id("VendorTinCardType")));
    dropdown.selectByVisibleText("VISA");
    driver.findElement(By.id("VendorCardHolderName")).sendKeys("TestName");

Without using if else i was able to run the script successfully but when I want to run else part its showing the error as

Unable to locate element: {"method":"xpath","selector":"/html/body/section[1]/div/article/nav/button[2]"}


Solution

  • As per code if first element is displayed then go for code in if, if that first element is not displayed then go for code in else.

    now simple thing here is, if the first element is not displayed then sure we will receive no element exception right? so we need handle this by try/catch.

    Boolean dd;
    
    try{
     dd = driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).isDisplayed();
    }catch(Exception e){
     //you can print as element not displayed
    }
    

    then go for if condition

     if(dd==true){
      //do something
      }else{
     //do some thing else
     }
    

    Thank You, Murali