How do I verify that an element does not exist in Selenium 2
You can use this:
Boolean exist = driver.findElements(By.whatever(whatever)).size() == 0;
If it doesn't exist will return true.
If you are testing using junit and that is the only thing you are testing you could make the test expect an exception using
@Test (expected=NoSuchElementException.class)
public void someTest() {
driver.findElement(By.className("commentEdit"));
}
Or you could use the findElements
method that returns an list of elements or an empty list if none are found (does not throw NoSuchElementException
):
...
List<WebElement> deleteLinks = driver.findElements(By.className("commentEdit"));
assertTrue(deleteLinks.isEmpty());
...
or
....
assertTrue(driver.findElements(By.className("commentEdit")).isEmpty());
....
I split out page classes so I don't have to define elements more than once. My nunit and mbunit test classes call those page classes. I haven't tried this out yet but this is how I'm thinking about doing it so I can use .exists() like I did with WatiN.
Extension Class:
public static class ExtensionMethods
{
public static IWebElement ElementById(this IWebDriver driver, string id)
{
IWebElement e = null;
try
{
e = driver.FindElement(By.Id(id));
}
catch (NoSuchElement){}
return e;
}
public static bool Exists(this IWebElement e)
{
if (e == null)
return false;
return true;
}
}
Page Class:
public IWebElement SaveButton { get { try { return driver.ElementById("ctl00_m_m_body_body_cp2_btnSave")); } }
Test Class:
MyPageClass myPageClass = new MyPageClass(driver);
if (myPageClass.SaveButton.Exists())
{
Console.WriteLine("element doesn't exist");
}