6

I've been using Selenium WebDriver to implement functional tests for some projects that I've worked with. I'm trying to use the Page Object design pattern with Page Factory to factor out my locators. I've also created a static WaitTool object (singleton) that implements several waiting techniques with optional timeout parameters.

My current problem is that I would like to use my wait methods before the PageFactory attempts to initialise the WebElements. The reason I would like to wait is because the PageFactory may try to initialise the page elements before they are available on the page.

Here is a sample PageObject:

public class SignInPage extends PageBase {
    @FindBy(id = "username")
    @CacheLookup
    private WebElement usernameField;

    @FindBy(id = "password")
    @CacheLookup
    private WebElement passwordField;

    @FindBy(name = "submit")
    @CacheLookup
    private WebElement signInButton;

    public SignInPage(WebDriver driver) {
        super(driver);

        WaitTool.waitForPageToLoad(driver, this);

        // I'd like initialisation to occur here
    }

    public MainPage signInWithValidCredentials(String username, String password){
        return signIn(username, password, MainPage.class);
    }

    private <T>T signIn(String username, String password, Class<T> expectedPage) {
        usernameField.type(username);
        passwordField.type(password);
        signInButton.click();

        return PageFactory.initElements(driver, expectedPage);
    }
}

Here is a sample TestObject:

public class SignInTest extends TestBase {
    @Test
    public void SignInWithValidCredentialsTest() {
        SignInPage signInPage = PageFactory.initElements(driver, SignInPage.class);

        MainPage mainPage = signInPage.signInWithValidCredentials("sbrown", "sbrown");

        assertThat(mainPage.getTitle(), is(equalTo(driver.getTitle())));
    }
}

I tend to put my logic in the Page Object as much as possible (including waits), as it makes the test cases much more readable.

4

1 回答 1

8

PageFactroy 中的 WebElements 实际上是 WebElements 的代理。这意味着每次访问 WebElement 时,它都会执行搜索以查找页面上的元素。

这有一些优点:

  • 初始化 PageFactory 时,代理已配置,但此时未找到 WebElement(因此您不会收到 NoSuchElementException)
  • 每次您使用 WebElement 时,它都会再次找到它,因此您不应该设置 StaleElementException's

您正在使用 @CacheLookup 注释,它失去了第二个好处,因为它会找到元素一次然后保留对它的引用,您现在更有可能看到 StaleElementExceptions。

话虽如此,您仍然保留了主要好处,即 Selenium 在您第一次使用它之前不会进入页面并实际找到该元素。

所以总而言之,你需要做的就是移动

PageFactory.initElements(driver, this);

进入您的构造函数,一切都会正常工作。

于 2013-04-24T05:45:52.870 回答