在我的测试中使用来自 PageFactory POM 的 WebElements class

Using WebElements from PageFactory POMs in my test class

基本上,我想断言(根据我的测试 class)WebElement 包含 text()。由于我所有的 WebElements 都在我的 page.class 中定义,我想我必须让它们 public 才能做到这一点。

我 运行 遇到了网络驱动程序和元素的一些问题,我认为这可能是因为多个测试 class 正在同时从页面 class 访问 WebElements。我的问题是:WebElements 必须是私有的有什么理由吗?

代码示例:

我看过的所有 PageFactory 教程都说要将您的 WebElements 设为私有,例如

    @FindBy(xpath = "//*[@id='searchStringMain']")
    private WebElement searchField;

但是要断言一个元素包含文本(来自另一个 class),我必须这样定义它们:

    @FindBy(xpath = "(//*[contains (text(),'Hrs')])[2]")
    public static WebElement yourLoggedTime;

考虑这个例子:

package org.openqa.selenium.example;

import org.openqa.selenium.By;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.WebElement;

public class GoogleSearchPage {
    // The element is now looked up using the name attribute
    @FindBy(how = How.NAME, using = "q")
    private WebElement searchBox;


    public void searchFor(String text) {
        // We continue using the element just as before
        searchBox.sendKeys(text);
        searchBox.submit();
    }
}

searchbox 是私有的,但 searchFor 方法是 public。测试将使用 searchFor 但从不使用 searchBox。

我通常将页面工厂 initElements 调用放在页面构造函数的最后一行。这使得所有 public 函数都可用于测试。所以

package org.openqa.selenium.example;

import org.openqa.selenium.By;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.WebElement;

public class GoogleSearchPage {
    public WebDriver driver;
    // The element is now looked up using the name attribute
    @FindBy(how = How.NAME, using = "q")
    private WebElement searchBox;

    public GoogleSearchPage(WebDriver driver) {
        this.driver = driver
        PageFactory.initElements(driver, this);
    }


    public void searchFor(String text) {
        // We continue using the element just as before
        searchBox.sendKeys(text);
        searchBox.submit();
    }
}

在你的测试中你可以这样做:

new GoogleSearchPage(webDriver).searchFor("Foo");

您可以保留 class 归档 public,但作为标准做法,建议使用 getter 方法归档 class 而不是直接归档访问。
问题是 static 关键字与 public 一起使用。当您将 @FindBy 注释与 filed (webelement) 一起使用时,它会在 class 初始化时初始化(或者取决于您调用 initElements() 的实现)。所以有 webelement public 没有 static 是可以的。例如:

在您的页面中 class:

@FindBy(xpath = "(//*[contains (text(),'Hrs')])[2]")
public WebElement yourLoggedTime;

测试中:

String yourLoggedTime = pageObj.yourLoggedTime.getText(); //pageObj is object of your page class