Assert for elementNotPresent on a page in Selenium WebDriver
- July 7th, 2011
- Posted in Selenium . selenium RC . webdriver . XPATH
- By Vemu
- Write comment
There would be some scenarios where we need to assert that a particular emenet is not present or element is hidden on a page.
we need to do the following to assertElementNotPresent:
Create a class by Name: public class Element
Inside the class Element.java add the following method by name isHidden()
public static Boolean isHidden( WebDriver webDriver, By by )
{
try
{
WebElement element = webDriver.findElement( by );
return false;
}
catch ( NoSuchElementException e )
{
return true;
}
}
what the above does is it gets the Element not found exception and returns true.
How to implement the above class and method:
In the actual test add the following:
assertTrue( Element.isHidden( getWebDriver(), By.xpath( xpathLocator ) ) );
I agree 100% with your comments
Hey there, I must say I’m a big fan of your website .
Hi vemu,
I need small favour, which am not able to get over of it. If particular element is not present on the page then i have to verify some text which is displaying on page or not.
For the i have written the code as below.
private WebElement Resultsheadlinedate() {
return findElement(By.xpath(“//div[@class='resultsheadlinedate']“));
}
public boolean isResultsHeadlineDatePresent() {
return Resultsheadlinedate().isDisplayed();
}
if(sixNation.isResultsHeadlineDatePresent()){
do something
}
else{
Assert.assertTrue(driver.isTextPresent(“some text”));
}
Since that particular element is not coming am expecting it should go to else statement but it doesn’t.
am getting “Unable to locate element:” any idea how to handel this?
Thanks in Advance,
Swathi
Hi Swathi,
The mistake you are doing is initially defining Resultsheadlinedate() and
polling for it so it will never be displayed and the element is not found.
Best way to do it is in the test itself write a test where you do not get
the element and then try to assert for the text
If you are not sure send me an email in detail to vemu@vemuvpk.com
Regards,
Vemu