在 Selenium 中使用页面工厂时如何显式等待?

How to explicitly wait while using page factory in Selenium?

我将像这样在 Selenium 中组织一个显式等待:

WebDriverWait = new WebDriverWait(driver,30);

WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(locator));

问题是我的 class 中没有驱动程序,因为我在测试中使用了 PageFactory,而不是构造函数 class:

MyClass myform = PageFactory.InitElements(driver, MyClass.class)

在这种情况下组织显式等待的好的决定是什么?

我建议您按预期使用 PageFactory,并为您的 class 提供一个构造函数,您希望在其中使用显式等待。脚本和页面对象之间的分离使得将来更容易使用。

public class MyClass {

    WebDriverWait wait; 
    WebDriver driver; 
    @FindBy(how=How.ID, id="locatorId")
    WebElement locator; 

    // Construct your class here 
    public MyClass(WebDriver driver){
        this.driver = driver; 
        wait = new WebDriverWait(driver,30);
    }

    // Call whatever function you want to create 
    public void MyFunction(){
        wait.until(ExpectedConditions.presenceOfElementLocated(locator));
        // Perform desired actions that you wanted to do in myClass
    } 

然后在您的测试用例中使用代码来执行您的测试。在您的示例中,等待包含在页面内。

public class MyTestClass {
    public static void main (string ... args){
        WebDriver driver = new FireFoxDriver(); 
        MyClass myForm = PageFactory.initElements(driver,Myclass.class); 
        myForm.MyFunction(); 
    }
}

此示例是根据可在此处 此处找到的 Selenium WebDriver 实用指南一书中的示例建模的

我认为更好的解决方案是在页面 class 中从其调用者测试 class 传递驱动程序。请参考下面的实现以获得更多清晰度。

第Class页:

public class YourTestPage {
    private WebDriver driver;
    private WebDriverWait wait;

    @FindBy(xpath = "//textarea")
    private WebElement authorField;

    public YourTestPage(WebDriver driver) {
        this.driver = driver;
        wait = new WebDriverWait(driver, 15, 50);
        PageFactory.initElements(driver,this);
    }

    public String getAuthorName() {
        wait.until(ExpectedConditions.visibilityOf(authorField)).getText();
    }
}

测试Class:

public class YourTest{

    private YourTestPage yourTestPage;
    private WebDriver driver;

    @BeforeTest
    public void setup() throws IOException {
      driver = WebDriverFactory.getDriver("chrome");
      yourTestPage = new YourTestPage(driver);
    }

    @Test
    private void validateAuthorName() {     
      Assert.assertEquals(yourTestPage.getAuthorName(),"Author Name");
    }
}