1

How to initialize the driver so it can be used by all classes

Hi All,

I am writing a test automation framework in JAVA using Appium, Selenium and Cucumber.

I start off by declaring an Appium Driver in one of my test step files and then this gets cast to an Android Driver or iOS Driver depending on the app under test.

I need some help please - I need all of my class files to have access to this instance of the driver but I’m not sure how to do this. The test is driven from the feature file and some of the test steps are in different class files so how can they all access this instance of the driver?

Thanks Matt

Matthew Hayhurst
  • 69
  • 1
  • 2
  • 8
  • Possible duplicate of [Sharing same selenium WebDriver between step definition files](https://stackoverflow.com/questions/31573676/sharing-same-selenium-webdriver-between-step-definition-files) – M.P. Korstanje Feb 03 '19 at 10:53
  • Have answered the ques, let me know if that helps. – Sameer Arora Feb 04 '19 at 16:49

3 Answers3

2

You can make an initialising method in the class where all the other config setup can be done and then you can make an instance of that class to call the getDriver method.
For example:

public class initialiseDriver{
private static AppiumDriver<MobileElement> driver;

public AppiumDriver<MobileElement> getDriver() throws IOException {
if (PLATFORM_NAME.equals("Android")) {
    // setup the android driver
} else if (PLATFORM_NAME.equals("iOS")) {
    // setup the ios driver
}
return driver;
  }
}

You can just call this method where you want to use the driver. Ideally, you should initialise the driver by calling this method in the @BeforeSuite/@BeforeClass method, so that you don't need to call this method everytime you start your script as it would be called implicitly with the @BeforeSuite/@BeforeClass.

Sameer Arora
  • 4,439
  • 3
  • 10
  • 20
0

you can define your AppiumDriver as static

public class AppiumHelper(){
   public static AppiumDriver<MobileElement> driver;

   public void setupDriver(){
       //define your DesiredCapabilities       

       //initialize your driver

  }

Then you can use your driver in your test method like

public void test1(){
       MobileElement element= AppiumHelper.driver.findElementById("elements id");

}
Suban Dhyako
  • 2,436
  • 4
  • 16
  • 38
0

The serenity PageObject class provides an inbuilt getDriver() method which you can call wherever you want to initialize the driver(preferably in the test classes). Avoid trying to initialize the driver in any of your step definations/step libraries(Managing using @Managed annotation) else it will throw a :

null pointer exception.