user2150250 user2150250 - 3 months ago 40
Java Question

Asserting Element Not Present Using ExpectedConditions Class

I'm trying to get into the practice of utilizing the ExpectedConditions class to do my Selenium related assertions, but I'm having trouble finding the de facto best practice for asserting a given element is not present. I'm trying to use something like this ...

Assert.assertFalse(ExpectedConditions.presenceOfElementLocated(By.xpath(myXpath)).apply(driver1));


But this won't compile of course because
presenceOfElementLocated
returns a WebElement instead of a boolean, which I'm finding frustrating. What do you recommend as the best practice for accomplishing what I'm going for?

EDIT: The accepted answer to the question converted to Java ...

public static boolean elementXpathPresent(WebDriver driver,String elementXpath) {
try {
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(elementXpath)));
} catch (TimeoutException e) {
return false;
}
return true;
}

Answer Source

Well, using ExpectedConditions will eventually throw NoSuchElementException if there is no element matching the selector present. In that case you probably want to use try catch with ExpectedConditions or simply use findElements() and size() to see if it finds any elements at all. See my answer here

Here is another option for you. Written in C# but will be fairly easy to convert

/// <summary>
/// 
/// </summary>
/// <returns></returns>
public bool Test()
{
    try
    {
        new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(
            ExpectedConditions.ElementExists(By.XPath("MyXpath")));
    }
    catch (NoSuchElementException)
    {
        return false;
    }

    return true;

}

/// <summary>
/// 
/// </summary>
public void Assertion()
{
    Assert.IsTrue(Test());
}