Assert Absence of element in the web page, giving

2019-06-08 20:58发布

问题:

Need to assert that there is no such element in the webpage, When tried with fieldValueBox.isDisplayed(); instead of "false" its throwing "NoSuchElementFound" exception. Right now i was using 'try catch' and making decision in 'catch'

回答1:

If the element is not on the page, then you will get 'NoSuchElementFound' exception. You can try checking that the number of elements with the locator is zero:

private boolean elementNotOnPage(){
    boolean elementIsNotOnPage = false;

    List<WebElement> element = driver.findElements(yourLocator);

    if(element.size() == 0){
        elementIsNotOnPage = true;
    }

    return elementIsNotOnPage;

}


回答2:

The isDisplayed() method returns a boolean based on an existing element. Meaning, if you want to check if an element, which exists, is displayed on the webpage or not (as in, not hidden or anything), this method will work properly.

In your case, its possible that the fieldValueBox does not exist. Because of this, the isDisplayed() method is going to try to return a boolean on a non-existing object.

A try catch is going to help you here, so that's one correct way. There are a few other ways, check:

WebDriver: check if an element exists?

How do I verify that an element does not exist in Selenium 2



回答3:

As you are trying to assert that there is no such element in the webpage you have :

fieldValueBox.isDisplayed();

Now if you look into the Java Docs of isDisplayed() method it's associated to the Interface WebElement. So before you invoke isDisplayed() method first you have to locate/search the element then only you can invoke isDisplayed(), isEnabled(), isSelected() or any other associated methods.

Of-coarse, in your previous steps when you tried to find/locate the desired WebElement through either findElement(By by) or findElements(By by) method NoSuchElementFound exception was raised. When findElement(By by) or findElements(By by) method raises NoSuchElementFound exception ofcoarse the following line of fieldValueBox.isDisplayed(); won't be executed.

Solution

A possible solution for your problem would be to invoke findElement(By by) within a try-catch {} block as follows :

try {
    WebElement fieldValueBox = driver.findElement(By.id("element_id"));
    bool displayed = fieldValueBox.isDisplayed();
    //use the bool value of displayed variable
} catch (NoSuchElementException e) {
    //perform other tasks
}