The purpose of passing the web driver object into page object base class's constructor The purpose of passing the web driver object into page object base class's constructor selenium selenium

The purpose of passing the web driver object into page object base class's constructor


By initializing WebDriver in a base class, you can use this base class to keep track of your driver for easy setup and teardown, in a way that is isolated from the rest of your code.

Elaborating on your code a bit:

public class Base {    public WebDriver driver;    public Base(WebDriver driver){        driver = this.driver;    }    [SetUp]    public WebDriver GetDriver()    {        // perform steps to initialize WebDriver        driver = this.driver    }    [TearDown]    public void DestroyDriver()    {        driver.Close();        driverQuit();    }}

Now, you can write test classes that inherit from Base. This gives you an instance of WebDriver to use in your code, and you don't have to perform Setup or Teardown in your test class either:

public class MyTestClass : Base{    // this test method will perform setup (inherited from base), run the test, then teardown (also inherited from base)    public void MyTest_1()    {        // perform webdriver actions in the test case        element = driver.FindElement(someSelector);        // initialize a PageObject        PageObject myPageObject = new PageObject(driver);        // perform some action using a PageObject        myPageObject.EnterTextIntoForm();    }}

You can also use this driver instance to initialize PageObjects:

public class MyPageObject{    public MyPageObject(driver)    { }    public void EnterTextIntoField    {       // we can use the same driver instance here        driver.FindElement(someSelector).SendKeys(someField);    }}

So this pattern allows your WebDriver instance to be used in test cases and page objects to perform all sorts of testing functions. You can abstract setup and teardown into the base class, and you will not have to write the same setup and teardown method over and over in your code.

The only downside to this approach is that it takes longer to write a framework and adds a layer of complexity to your code. But there is really no down side, and abstracting your WebDriver into a base class as such is usually considered best practice.