4

I am a Software tester who has a very basic knowledge of java and Selenium2. I am trying to write a Junit Selenium2 test to click on an item if it appears on the page.(The majority of the time this item should not appear) if it is not there then i would like the code to just click an alternative item. I have tried using an if else statement. My code is shown below.When i execute the code it just results in an error.(NoSuchElementException) because it can't find the id "house". plwease could someone help.

@Test
 public void testMyLoop() throws Exception {
    if (driver.findElement(By.id("house")).isDisplayed()) {
        driver.findElement(By.id("house")).sendKeys("test");
    } else {
        driver.findElement(By.linkText("Garage")).click();
    }
}

1 Answer 1

4

Your immediate problem is that Selenium throws an exception when it fails to find an element whose id is "house". Here are two ways to get past that problem: you can either catch the NoSuchElementException like this:

@Test
public void testMyLoop() throws Exception {
  boolean houseDisplayed = false;
  try {
     WebElement e = driver.findElement(By.id("house"));
     houseVisible = e.isDisplayed();
   }
   catch (NoSuchElementException ex) {}
   if (houseDisplayed) {
     driver.findElement(By.id("house")).sendKeys("test");
   }   else  {
     driver.findElement(By.linkText("Garage")).click();
   }
}

or you can replace findElement with a different method that does not throw a NoSuchElementException:

@Test
public void testMyLoop() throws Exception {
  boolean houseDisplayed = false;
  List<WebElement> elist = driver.findElements(By.id("house"));
  if (elist.count() == 1) {
     WebElement house = elist.get(0);
     houseDisplayed = house.isDisplayed();
  }
  if (houseDisplayed) {
     driver.findElement(By.id("house")).sendKeys("test");
   }   else  {
     driver.findElement(By.linkText("Garage")).click();
   }
}

Caveat: these code fragments may not compile as is and can be written in a cleaner way, but I hope they illustrate how to get past your immediate problem.

I have not seen the HTML for your page, so I cannot offer an opinion about whether you are identifying the house and Garage elements correctly.

1
  • Thank you for your help. This has helped me solve the problem. Commented Oct 12, 2011 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.