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!
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");
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.