title: Using PageObjects, Page Factory and WebDriverWait in Selenium WebDriver using Java
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>Here is a sample PageObject:</p>
  
  <pre><code>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 &lt;T&gt;T signIn(String username, String password, Class&lt;T&gt; expectedPage) {
          usernameField.type(username);
          passwordField.type(password);
          signInButton.click();
  
          return PageFactory.initElements(driver, expectedPage);
      }
  }
  </code></pre>
  
  <p>Here is a sample TestObject:</p>
  
  <pre><code>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())));
      }
  }
  </code></pre>
  
  <p>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.</p>