Reputation: 955
I have seen the web driver object is having in the page object base class level's constructor as follows.
Example:
public class PageObjectBase
{
protected WebDriver driver;
public PageObjectBase(WebDriver driver){
driver = this.driver;
}
}
public class LoginPage extends PageObjectBase
{
public LoginPage(WebDriver driver){
super(driver);
}
}
What are the advantages and disadvantages of this approach? Why are we always passing driver object to base constructor?
Upvotes: 4
Views: 1944
Reputation: 5909
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.
Upvotes: 3