Please post your Web Driver questions in official Web Driver forum

Monday, December 1, 2014

How to avoid null pointer exception?

While writing selenium tests we often come across verification points which deal with verifying attributes/properties of an html element. Consider following example

WebElement webElement = driver.findElement("testEElement"));
assert webElement.getAttribute("class").equalsIgnoreCase("highlight")

This example seems seemingly simple but there is catch. What if attribute class is missing?
In this case, evaluation of second statement will throw null pointer exception. Hence a better approach would be to compare String "hightlight" with attribute of webelement. that is -

assert "highlight".equalsIgnoreCase(webElement.getAttribute("class"))

And this will return false if element attribute is missing from element because of an application defect.
Fork me on GitHub