Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Webdriver: best practice to handle a NoSuchElementException

After much searching and reading, I'm still unclear as to the best way to handle a failed assertion using Webdriver. I would have thought this was a common and core piece of functionality. All I want to do is:

  • look for an element
  • if present - tell me
  • if not present - tell me

I want to present the results for a non technical audience, so having it throw 'NoSuchElementExceptions' with a full stack trace is not helpful. I simply want a nice message.

My test:

@Test
public void isMyElementPresent(){
  //  WebElement myElement driver.findElement(By.cssSelector("#myElement"));
    if(driver.findElement(By.cssSelector("#myElement"))!=null){
        System.out.println("My element was found on the page");
    }else{
            System.out.println("My Element was not found on the page");
        }
    }

I still get a NoSuchElementException thrown when I force a fail. Do I need a try/catch as well? Can I incorporate Junit assertions and/or Hamcrest to generate a more meaningful message without the need for a System.out.println?

like image 628
Steerpike Avatar asked Apr 01 '14 08:04

Steerpike


People also ask

What is NoSuchElementException in Selenium?

What is a NoSuchElementException in Selenium? NoSuchElementException is one of the most common exceptions in Selenium WebDriver, and it is thrown when an HTML element cannot be found. A NoSuchElementException occurs when the Selenium locator strategy defined is unable to find the desired HTML element in the web page.


1 Answers

I have encountered similar situations. According to the Javadoc for the findElement and findElements APIs, it appears that the findElement behavior is by design. You should use findElements to check for non-present elements.

Since in your case, there's a chance that the WebElement is not present, you should use findElements instead.

I'd use this as follows.

List<WebElement> elems = driver.findElements(By.cssSelector("#myElement"));
if (elems.size == 0) {
        System.out.println("My element was not found on the page");
} else
        System.out.println("My element was found on the page");
}
like image 81
Vish Avatar answered Sep 19 '22 13:09

Vish