title: Initialising PageFactory just once in a separate java class
body: <p>I am trying to reduce the verbosity in my script, following the Don't Repeat Yourself (DRY) coding practice. I stumbled on a challenge. I have implemented a basic test using selenium and cucumber with pagefactory. I have my page objects in one separate <code>BasePage</code> class and initialised pagefactory in another <code>Test</code> class. The initialisation is taking place inside every method and the test runs as expected.</p>
  
  <pre><code>public class Test {
  private static WebDriver driver;
  
  public void navigateToUrl(String url) {
  //Launch browser
  }
  
  public void firstLogin(String username, String Password) {
  BasePage basePage = PageFactory.initElements(driver, BasePage.class); //Initialisation
  basePage.usernameField.click();
  basePage.passwordField.sendKeys("pwd");
  }
  
  public void secondLogin()  {
  BasePage basePage = PageFactory.initElements(driver, BasePage.class); //Initialisation
  basePage.myIdField.click();
  basePage.myPasswordField.click();    
  }
  </code></pre>
  
  <p>I am trying to enhance the script. I want to initialise pagefactory just once, perhaps at class level, and not initialise inside every method, so, I took off the initialisation from all the methods and declared it once at class level:</p>
  
  <pre><code>public class Test {
  private static WebDriver driver;
  BasePage basePage = PageFactory.initElements(driver, BasePage.class); //Initialisation
  </code></pre>
  
  <p>I got a nullpointerException.</p>
  
  <p>I also tried this, putting the initialisation in a setup method:</p>
  
  <pre><code>public class Test {
  private static WebDriver driver;
  private static BasePage basePage;
  
  @BeforeMethod
  public void setUp() {
  basePage = PageFactory.initElements(driver, BasePage.class);
  }
  </code></pre>
  
  <p>Still, It resulted in Nullpointer</p>
  
  <p>My <code>BasePage</code> header looks like this:</p>
  
  <pre><code>public class BasePage {
  private final WebDriver driver;
  
  public BasePage(WebDriver driver) {
     this.driver = driver;
    }
  </code></pre>
  
  <p>Not only am I initialising multiple times, I am also using the <code>basePage</code> variable in every line in the <code>firstLogin</code> and <code>secondLogin</code> methods. Whether there is a way round that, I dont know, but it would be helpful if someone can advise or give an input. Thanks.</p>