How to initialize the driver globally in selenium



    • I wanted to create a separate class to initialize the firefox driver and then use the driver instance in my other TestNG classes.
    • Can someone tell me how to do this and how to use the same driver instance in all other test classes


  • One way is to use a singleton class like this:

    public class FirefoxDriverProvider {
        private static FirefoxDriver instance = null;
        public static FirefoxDriver getInstance() {
            if (instance == null) {
                instance = ... initialize FirefoxDriver here ...;
            }
            return instance;
        }
    }
    
    In your TestNG classes, you can do this:
    
        FirefoxDriver instance = FirefoxDriverProvider.getInstance();
    

    Experienced developers will tell you that it is a bad practice to use a Singleton pattern. The reasoning behind that is beyond the scope of this question.

    An alternative would be to use a dependency injection framework such as Spring. (Questions about Spring belong on StackOverflow, not here.)



Suggested Topics

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