如何在Selenium中使用页面工厂时明确等待?

7ca*_*ect 4 java selenium webdriver pageobjects selenium-webdriver

我将在Selenium组织一次明确的等待,如下所示:

WebDriverWait = new WebDriverWait(driver,30);

WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(locator));
Run Code Online (Sandbox Code Playgroud)

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

MyClass myform = PageFactory.InitElements(driver, MyClass.class)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,组织明确等待的好决定是什么?

小智 7

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

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
    } 
Run Code Online (Sandbox Code Playgroud)

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

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

这个例子是按照Selenium WebDriver实用指南中的例子建模的,可以在这里找到

  • 嗨,我尝试使用 wait.until(ExpectedConditions.presenceOfElementLocated(locator)); 但presenceOfElementLocated 不会将“WebElement”作为输入。你能解释一下吗。 (3认同)