In this first refactoring, we will remove the manual dependency of starting and stopping the Appium server, and we will do it programmatically:
- Create a new class called StartingSteps under the steps package
- In the StartingSteps class, create two empty methods, called startAppiumServer and stopAppiumServer:
public void startAppiumServer(){
//code to start appium server
}
public void stopAppiumServer(){
// Code to stop appium server
}
At this point in time, we need to know the concept of hooks in cucumber. So basically, cucumber gives you a number of hooks, which allow one to run certain code at a certain point in the test life cycle. These hooks can be used and defined in a class file in the steps folder. However, cucumber doesn't mandate the location. So, the two hooks that we will use are these:
- Before: Before hooks will run before the execution of each scenario. They execute before the first step mentioned in each scenario; hence, they can potentially act as a common setup for all the tests. We can have multiple before hooks, and they will run in the same order as they are declared.
- After: After hooks run after the last step of each scenario. they run irrespective of the outcome of the last step, whether the last step is a success or failure.
Let's put the @Before tag for the startAppiumServer method and the @After tag for stopAppiumServer method. While resolving, ensure that you use the cucumber.api.java, highlighted here:
- The next step is to add code that will start the Appium server. Appium exposes AppiumDriverLocalService, which will basically let you start and stop the server.
- Add the following code to the startAppiumServer method. So, this builds the default Appium service, which means that the IP address will remain 0.0.0.0 and the port will be 4723:
@Before
public void startAppiumServer() throws IOException {
AppiumDriverLocalService appiumService =
AppiumDriverLocalService.buildDefaultService();
appiumService.start();
}
- To implement the stopAppiumServer method, we need appiumService to be in instance variable; so, highlight the first row above and select Refactor > Extract > Field.
- Once done in the stopAppiumServer method, implement the following code. This stops the Appium server:
@After
public void stopAppiumServer() {
appiumService.stop();
}
- Once done, stop any instance of Appium server running via the terminal (Command prompt in case of Windows) or Appium GUI app.
- Navigate to the feature file, right-click, and select the Run 'Feature:Sample' option.
You should be able to run both the scenarios without having to start the Appium server manually.