-2

I am trying to fill up a dynamic from which is automatically generated with user info. So I want to set if else condition for field of the from. So i use if else loop in step defenition but suppose if condition true its ok the code excute but if "if condition fail the code stuck in else loop why.Please help

The code is below

 @And("^Input Height in add report$")
 public void Input_Height_in_add_report(DataTable newHeight) throws Throwable {
  
  
  if(driver.findElement(By.xpath("//label//span[contains(text(),'Height')]")).isDisplayed()){
   Thread.sleep(2000);
   List<List<String>> data = newHeight.raw();
   driver.findElement(By.xpath("/html/body/div[1]/div/div/div[2]/form/div[7]/div[1]/div/div/input")).sendKeys(data.get(1).get(1));
    }
  else{
   
  }
 
 }
MD XF
  • 7,860
  • 7
  • 40
  • 71
Mithu Khan
  • 57
  • 1
  • 6

1 Answers1

0

The problem is that if findElement finds the element it goes if statement but if it doenst find the element it gives NosuchElementFound exception. To handle this yo can use try-catch block to run code in the else, check the following:

@And("^Input Height in add report$")
public void Input_Height_in_add_report(DataTable newHeight) throws Throwable {

  try {
    if(driver.findElement(By.xpath("//label//span[contains(text(),'Height')]")).isDisplayed()){
      Thread.sleep(2000);
      List<List<String>> data = newHeight.raw();
      driver.findElement(By.xpath("/html/body/div[1]/div/div/div[2]/form/div[7]/div[1]/div/div/input")).sendKeys(data.get(1).get(1));
    }
  }
  catch(Exception e) {

  // your else code should be here

  }
}
Mesut GUNES
  • 7,089
  • 2
  • 32
  • 49
  • I don't want to execute any other code for else condition, should i leave it blank. – Mithu Khan Jan 12 '17 at 09:08
  • @MithuKhan you can print or log the exception for debugging later if you want. May you accept answer and up it? – Mesut GUNES Jan 13 '17 at 14:23
  • Before accepting the answer I want to run the test with your code. I am telling you if I leave the catch(){}, Blank is it a problem or not? I mean if i don't write anything in else code catch(Exception e) { // your else code should be here } leave as it now is it going to be a problem or i have to execute a code in else condition.I ma bigginer in java – Mithu Khan Jan 13 '17 at 19:52
  • exception block works when try doesn't work with your code, if you don`t want to handle catch block leave it empty. Also this platform aims to give you an idea for the solution, not copy and paste coding – Mesut GUNES Jan 14 '17 at 19:27
  • This solution didn't work , same result it stuck if condition is false – Mithu Khan Jan 17 '17 at 06:06