Search code examples
javaseleniumselenium-webdriverpage-factory

Two instance of WebDriver created


I am new to Selenium as well as Java. I am trying to implement the POM-PageFactory model. My testng method is launching 2 instances of WebDriver.

I have a BaseClass that hold driver object and an init method responsible for calling the right drive.exe based on browser. The PageClass is the page object repository with few utility methods. The TestClass has the test methods. If I invoke the init method within TestClass my code works fine. However I intend to invoke within the BaseClass. If I do this then 2 instances of driver objects are created. Please see the code below

public class BaseClass {
public static WebDriver driver;
public BaseClass() {
    init("chrome");
    //if init is invoked with in TestClass code is fine
            //do not know what to do here if init call is removed
}
public void init(String browser) {
    switch(browser) {// instantiate driver based on browser
    case "chrome": 
        driver = new ChromeDriver();
        break;
    }
}
public void navigate(String url) {
   //open website
}
}

 public class PageClass extends BaseClass{
  @FindBy()
  WebElement searchTxtBox;
  //other elements here

  public PageClass() {
    PageFactory.initElements(driver, this);
  }

  public void enterSearchText(){
      //page specific methods
  }
 }

public class TestClass extends BaseClass {
  PageClass page;

  public TestClass() {
    super();
  }
@BeforeClass
public void launch() {
    // init("chrome"); .....if init() moved to BaseClass
            // then 2 instances of Chrome driver is launched
    page = new PageClass(); 
  }
@Test
public void searchForSomething() 
  {
    navigate("https://google.com");
    page.enterSearchString("Selenium");
    page.clickSearchBtn();
  }
}

Solution

  • 2 instances are created because you invoke BaseClass twice.

    You see, when using @BeforeClass annotation, you are creating an instance of PageClass which inherits from BaseClass. Because of inheritance, you are calling the constructor of PageClass and default constructor of BaseClass. In @BeforeClass you create the first driver.

    Then, in TestClass class you create the second instance of a WebDriver because TestNG creates an instance of TestClass and again - constructor of TestClass invokes default constructor in BaseClass.

    That's why you have 2 instances of WebDriver