Search code examples
c#seleniumtestingreadonly-collection

Selenium: FindsBy with collection


I am a beginner in testing and have a question. How can I correctly use ReadOnlyCollection<IWebElement>if I use attribute FindsBy . My collection is always null after started test. Heres is my code in C#:

        [FindsBy(How = How.Name, Using = "role")]
        public ReadOnlyCollection<IWebElement> radPercentage { get; }

and here is testing web: http://testwisely.com/demo/survey

I want to do something like this: radPercentage[2].Click();


Solution

  • You need to call InitElements before using the collection. Pass the driver and an instance of a class containing the FindsBy properties (in my code "this").

    IWebDriver driver = new FirefoxDriver();
    driver.Navigate().GoToUrl("http://testwisely.com/demo/survey");
    PageFactory.InitElements(driver, this);
    IWebElement radio = this.radPercentage[2];
    

    The method InitElements is expecting the property to be of type IWebElement or IList of IWebElement

    [FindsBy(How = How.Name, Using = "role")]
    public IList<IWebElement> radPercentage;