1
  • 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
  • I would STRONGLY recommend against this. While it will speed up test execution, at what costs? – Paul Muir May 25 '16 at 13:33
  • I got this recommendation after reviewing my scripts from senior where i was initializing the driver in each class. So it was asked to be done in this way. – K.K May 25 '16 at 13:37
  • The solution provided by user246 should suffice. The issue with doing this is that by only initializing the WebDriver once it can run into issues where if something occurs with the driver in a previous test, something goes wrong or the state of the driver's instance is not in a predictable state it can cause issues. This is just a standard 'rule of thumb' and can obviously be worked around. If your requirements are as stated, fulfill them. For other people attempting to accomplish this I would suggest not doing it. – Paul Muir May 25 '16 at 13:39
  • Wisdom (or folly) of using Singleton pattern for settings will be better asked on Programmers exchange. If fact, it already was, multiple times – Peter M. - stands for Monica May 25 '16 at 14:32
  • IOW, if someone "senior" gives you advice, it does not mean s/he knows what s/he is doing. Use your own brains. – Peter M. - stands for Monica May 25 '16 at 14:34
5

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.)

  • When i write the FirefoxDriver instance = FirefoxDriverProvider.getInstance(); in my TestNG class i get error asking to declare the method getInstance in FirefoxDriverProvider class – K.K May 25 '16 at 14:02
  • Please find someone at your workplace who has experience coding in Java. – user246 May 25 '16 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.