简体   繁体   中英

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

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

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.

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");

}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM