Home > Enterprise >  PageFactory.InitElements with Selenium 4
PageFactory.InitElements with Selenium 4

Time:02-05

I want to update my legacy project selenium library to newest. Unfortunately I am facing problems with PageFactory.InitElements method (which is by default unavailable in Selenium 4, but available in DotNetSeleniumExtras.PageObjects). This is my example code:

class Program
{
    static void Main(string[] args)
    {
        var options = new FirefoxOptions();
        options.BrowserExecutableLocation = @"C:\Program Files\Mozilla Firefox\firefox.exe";

        var firefoxDriverService = FirefoxDriverService.CreateDefaultService("d:\\gecko");
        firefoxDriverService.HideCommandPromptWindow = true;

        var driver = new FirefoxDriver(firefoxDriverService, options);
        driver.Navigate().GoToUrl("SITE_URL");

        var loginPage = new LoginPage(driver);
        loginPage.EnterLogin("foo");
    }
}

public class LoginPage
{
    public IWebDriver Driver { get; private set; }

    [FindsBy(How = How.XPath, Using = "//input[contains(@id,'login_btn')]")]
    public IWebElement LoginTextField { get; protected set; }

    public LoginPage(IWebDriver driver)
    {
        Driver = driver;
        PageFactory.InitElements(Driver, this);
    }

    public void EnterLogin(string login)
    {
        LoginTextField.SendKeys(login);
    }
}

If I run this, I am getting error on PageFactory.InitElements line:

System.TypeLoadException: Could not load type 'OpenQA.Selenium.Internal.IWrapsElement' from assembly 'WebDriver, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null'

If I change packages configuration from:

DotNetSeleniumExtras.PageObjects 3.11.0
Selenium.WebDriver 4.1.0

to:

DotNetSeleniumExtras.PageObjects 3.11.0
Selenium.WebDriver 3.141.0

It works fine. Seems like a new version of Selenium doesn't like legacy PageFactory.InitElements. Is there anything I can do about it? I would like to have my page object classess as they are right now, because there are many of them.

CodePudding user response:

maybe this will solve your problem. The import is as follows:


import org.openqa.selenium.support.PageFactory;

And Page Factory initialisation is as follows (I have configured it so you can just copy/paste it) :

public LoginPage (){
        PageFactory.initElements(driver, this);
    }

CodePudding user response:

you cannot use PageFactory class and FindsBy attribute to store element when you use selenium version 4.1.0, instead create as a property for IWebElement/By type and it resolves this issue,I hope this solves your issue. Link to similar issue

  •  Tags:  
  • Related