简体   繁体   English

定位器和页面 Object Model

[英]Locators and Page Object Model

I want to use Playwright's Locators in my page objects.我想在我的页面对象中使用 Playwright 的定位器 I found an example for Javascript (stripped for brevity):我找到了Javascript 的示例(为简洁起见,已删除):

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:尝试在我的 Java 代码中做同样的事情:

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 .抛出 null 指针异常,因为在初始化loginButtonpage尚未启动。

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.但是对于大页面 object 类来说,这会变得有点冗长/混乱。

Any ideas on how to do that in Java?关于如何在 Java 中做到这一点的任何想法?

Thanks!谢谢!

You could put the Locator definition inside the constructor:您可以将 Locator 定义放在构造函数中:

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:我可以创建一个定位器 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() .然后通过例如 locators.LoginButton.click locators.LoginButton.click()访问页面 object class 中的定位器。

It wouldn't avoid the clumsiness/ messiness, but at least hide it from the page object class.它不会避免笨拙/混乱,但至少将其从页面 object class 中隐藏起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM