Take the 2-minute tour ×
Software Quality Assurance & Testing Stack Exchange is a question and answer site for software quality control experts, automation engineers, and software testers. It's 100% free, no registration required.

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();
            }
}
share|improve this question
add comment

1 Answer 1

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.

share|improve this answer
    
Thank you for your help. This has helped me solve the problem. –  Klugsminator Oct 12 '11 at 14:41
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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