I have started creating a framework in Selenium Webdriver in C#. I have a base class and a HomePage class. HomePage inherits the base class. When I instantiate the HomePage class I am getting the error:
A field initializer cannot reference the non static field, method or property autobot_automation.Base.BasePageDriver.get
I have declared the driver variable in the base class and initialised it in the constructor. I do not know why the compiler is showing the error.
My Base Class is:
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
using autobot_automation.Pages.HomePage;
using autobot_automation.Pages.Base;
namespace autobot_automation.Base
{
public class BasePage
{
public IWebDriver Driver { get; set; }
public BasePage(IWebDriver driver)
{
Driver = driver;
PageFactory.InitElements(Driver, this);
}
public void GoToURL(string url)
{
Driver.Navigate().GoToUrl(url);
}
#region Page Objects
public HomePage homepage = new HomePage(Driver);
#endregion
}
}
My HomePage Class is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
using autobot_automation.Pages;
using autobot_automation.Base;
namespace autobot_automation.Pages.HomePage
{
public class HomePage : BasePage
{
//private IWebDriver Driver { get; set; }
public HomePage(IWebDriver driver) : base(driver)
{
//Driver = driver;
//PageFactory.InitElements(Driver, this);
}
}
}
Suggestions please to help me resolve this. Thanks
The line public HomePage homepage = new HomePage(Driver);
in BasePage
will be executed before the constructor. It will create new HomePage
object with the driver
(null
at this point) which in turn initialize the Driver
property with null
.
I suggest you create some kind of support class which will hold the HomePage
instance instead of BasePage
.
If you insist on keeping it there (not a good design IMHO) creat a constructor which will receive a HomePage
object as parameter.