Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use selenium 2 PageFactory init Elements with Wait.until()?

The code snippet below works fine, but I'm having a little trouble with the wait.until() line:

wait.until(new ElementPresent(By.xpath("//a[@title='Go to Google Home']")));

It works but I want to send my PageFactory WebElement homePageLink instead:

wait.until(new ElementPresent(homePageLink));

Is there any way to do that?

These new fangled Selenium 2 features have got my head in a bit of a spin and I can't find much documentation.

Thanks.

public class GoogleResultsPage extends TestBase {

    @FindBy(xpath = "//a[@title='Go to Google Home']")
    @CacheLookup
    private WebElement homePageLink;

    public GoogleResultsPage() {  
        wait.until(new ElementPresent(By.xpath("//a[@title='Go to Google Home']")));
        assertThat(driver.getTitle(), containsString("Google Search"));
    }  
}

public class ElementPresent implements ExpectedCondition<WebElement> {

    private final By locator;

    public ElementPresent(By locator) {
        this.locator = locator;
    }

    public WebElement apply(WebDriver driver) {
        return driver.findElement(locator);
    }
}
like image 924
Bill Avatar asked Jul 17 '10 19:07

Bill


1 Answers

I use PageFactory with AjaxElementLocatorFactory - PageFactory is a support class for the Selenium 2 Page Objects pattern which you are using, and the AjaxElementLocatorFactory is the factory for the element locators. In your case the constructor will looks like:

public GoogleResultsPage() { 
    PageFactory.initElements(new AjaxElementLocatorFactory(driver, 15), this);
}

This code will wait maximum of 15 seconds until the elements specified by annotations will appear on the page, in your case the homePageLink which will be located by xpath. You will not need to use ElementPresent class.

like image 108
Sergii Pozharov Avatar answered Oct 12 '22 13:10

Sergii Pozharov