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:
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?
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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With