'Locators and Page Object Model
I want to use Playwright's Locators in my page objects. I found an example for Javascript (stripped for brevity):
import { Page } from '@playwright/test';
export class TodoPage {
listItems = this.page.locator('.todo-list li');
constructor(public readonly page: Page) { }
}
Trying to do the same in my Java code:
public class LoginPage {
private Page page;
private Locator loginButton = this.page.locator("#loginButton");
public LoginPage(Page page){
this.page = page;
}
}
throws a null pointer exception, because page is not yet initiated, when initializing loginButton.
I could do
private Locator loginButton;
public LoginPage(Page page){
this.page = page;
loginButton = this.page.locator("#loginButton");
}
but this would become kind of lenghty/ messy, for large page object classes.
Any ideas on how to do that in Java?
Thanks!
Solution 1:[1]
I could create a Locator class:
public class LoginPageLocators {
public Locator LoginButton;
public LoginPageLocators(Page page) {
LoginButton = page.locator("#loginButton");
}
}
And then access the locators in the page object class via eg locators.LoginButton.click().
It wouldn't avoid the clumsiness/ messiness, but at least hide it from the page object class.
Solution 2:[2]
You could put the Locator definition inside the constructor:
public class LoginPage {
private Page page;
private Locator loginButton;
public LoginPage(Page page){
this.page = page;
this.loginButton = this.page.locator("#loginButton");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Christian Baumann |
| Solution 2 | Peter Jenkins |
