Using multiple instances of webDriver



  • I have defined an object of Web driver in one class as

    Static WebDriver driver;
    

    and want to use that instance in another class to automate the browser. Is it possible? Or will I have to define drivers every time in each class?

    I tried by defining a webdriver in another class as:

    Static webDriver AnotherDriver; 
    

    and then assigning it the value of other driver as:

    AnotherDriver = ClassName.driver;
    

    But I am getting nullPointer Exception when I using AnotherDriver.

    And if I have to define a new driver in each class then I will get stuck, as I have defined some methods which I will be using in other class file and all of them use the driver defined in that class.

    Any kind of suggestion is highly appreciated.



  • Approach 1

    • Create a class, for example Hull.
    • In the class is a protected variable WebDriver driver.
    • In the class is a method setup() with a @Before annotation.
    • In the method you has a condition: Is WebDriver null, initialize; else do nothing.
    • Classes with test cases extends from Hull.
    • Classes with test cases can use the variable driver.

    Approach 2

    • Create a class, for example Hull.
    • In the class is a private variable WebDriver driver.
    • In the class is a method getDriver().
    • In the method you has a condition: Is WebDriver null, initialize; else do nothing.
    • Classes with test cases extends from Hull.
    • Classes with test cases can use the getDriver() method to use the WebDriver. Tip: Use always this method if you interact with the WebDriver, because so you are save that the WebDriver will be initialized.


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2