There are multiple reasons for that. But first let's fix this code first:
class LoginPage(){
WebDriver driver; //here you have global variable for this page object
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
}
You will want to have access to driver instance. You will need in more complicated PageObject some methods that will use any of methods implemented in Selenium such as: wait
, findElement
, getCurrentUrl
and many more
Secondly your test will have some Steps where you actually create static instance of driver for example (using JUnit 4)
public class LoginTest {
static WebDriver driver; //again global variable for test
@Before
public void setUp() {
driver = new ChromeDriver();
driver.get("https://google.com/");
}
@Test
public void testLoginPage() {
LoginPage loginPage = new LoginPage(this.driver);
// then perform some steps assertions
// and use another pageobject
OtherPage otherPage = new OtherPage(this.driver);
}
}
With this approach you are certain that:
- Always page objects in one test class will have the same instance of driver.
- Your page objects actually doesn't need to know anything about specific driver (if you change in your Test Class
ChromeDriver()
to FirefoxDriver()
your page objects are good to go.
And that's why this approach is so common. Because it prevents a bunch of issues and reduce maintenance time for fixing tests.