NikolaiDante
NikolaiDante

Reputation: 18649

Check for existance of an IWebElement when using PageObjects with Selenium

I am using PageObjects pattern with Selenium web driver, e.g.

  public class CategoryPage
  {
        private IWebDriver driver;

        [FindsBy(How = How.CssSelector, Using = ".notFound")]
        private IWebElement products;

        public CategoryPage(IWebDriver webDriver)
        {
            driver = webDriver;
        }

        public bool IsProductList
        {
            get
            {
                return products != null; // always true.
            }
        }

        // other stuff
  }

I am populating it via:

  var page = new CategoryPage(driver);
  PageFactory.InitElements(driver, page);
  return page;

When looking at a page the IsProductList check I have is always returning true, even when I set the selector to a class or css path that isn't on the page.

How should I be checking for existence?

Upvotes: 2

Views: 951

Answers (1)

Florent B.
Florent B.

Reputation: 42528

To determine if an element is present, you can use IList<IWebElement> to declare the page object and .Count to know if there is at least one element:

public class CategoryPage {
    private IWebDriver driver;

    [FindsBy(How = How.CssSelector, Using = ".notFound")]
    private IList<IWebElement> products;

    public CategoryPage(IWebDriver webDriver) {
        driver = webDriver;
    }

    public bool IsProductList {
        get {
            return products.Count > 0;
        }
    }

    // other stuff
}

Another way would be to catch the NoSuchElementException :

public class CategoryPage {
    private IWebDriver driver;

    [FindsBy(How = How.CssSelector, Using = ".notFound")]
    private IWebElement products;

    public CategoryPage(IWebDriver webDriver) {
        driver = webDriver;
    }

    public bool IsProductList {
        get {
            try {
                return products.Equals(products);
            } catch (NoSuchElementException) {
                return false;
            }
        }
    }

    // other stuff
}

Upvotes: 1

Related Questions