WebDriver: How to check if an page object web element exists?

后端 未结 8 1572
鱼传尺愫
鱼传尺愫 2020-12-25 14:13

How to check if an Element exists, when using Page Objects with webdriver.

So far I am doing it this way.

DefaultPage defaultPage = PageFactory.initE         


        
相关标签:
8条回答
  • 2020-12-25 14:43

    Webdriver is designed to throw an exception if an element is not found, So there aren't any methods to verify presence of an element in Webdriver.

    Check this - http://groups.google.com/group/webdriver/browse_thread/thread/909a9b6cb568e341

    0 讨论(0)
  • 2020-12-25 14:43

    I recently came across this old post and believe I've found one solution.

    I was testing a page that had an Add User button. When the button was clicked, various editable text fields appeared (for First Name, Last Name, Email, etc..) and a single dropdown.

    When a Cancel button was clicked, the fields disappeared and no longer existed. Using WebDriverWait with ExpectedConditions.visibilityOf() would not work since the elements no longer existed in the DOM.

    I found that @FindAll was a solution for me, though I must admit my test ran noticeably slow at the my List assertion.

    For your code, something like this:

    public class DefaultPage {     
    @FindAll({@FindBy(id = "link_i_user_create")}) List<WebElement> userCreateMenuLink;
    
    
    public boolean isUserCreateMenuLinkPresent() {
        if (this.userCreateMenuLink.isEmpty()) fail("Link does not exist");}
    

    I am able to use something similar in my own tests though, and it seems like a dependable way to skirt the 'No such element' exception. It's basically a page object adaptation of asserting: driver.findElements(By.locator).size() < 1.

    0 讨论(0)
提交回复
热议问题