Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Writing Your First Cucumber Appium Test

Save for later
  • 12 min read
  • 27 Jun 2017

article-image

In this article, by Nishant Verma, author of the book Mobile Test Automation with Appium, you will learn about creating a new cucumber, appium Java project in IntelliJ. Next, you will learn to write a sample feature and automate, thereby learning how to start appium server session with an app using appium app, find locators using appium inspector and write java classes for each step implementation in the feature file. We will also discuss, how to write the test for mobile web and use Chrome Developer Tool to find the locators. Let's get started!

In this article, we will discuss the following topics:

  • Create a sample Java project (using gradle)
  • Introduction to Cucumber
  • Writing first appium test
  • Starting appium server session and finding locators
  • Write a test for mobile web

(For more resources related to this topic, see here.)

Create a sample Java project (using gradle)

Let's create a sample appium Java project in IntelliJ. Below steps will help you do the same:

  • Launch IntelliJ and click Create New Project on Welcome Screen.
  • On the New Project screen, select Gradle from left pane. Project SDK should get populated with the Java version.
  • Click on Next, enter the GroupId as com.test and ArtifactId as HelloAppium. Version would already be populated. Click on Next.
  • Check the option Use Auto-Import and make sure Gradle JVM is populated. Click on Next.
  • Project name field would be auto populated with what you gave as ArtifactId. Choose a Project location and click on Finish.
  • IntelliJ would be running the background task (Gradle build) which can be seen in the status bar.
  • We should have a project created with default structure.
  • Open the build.gradle file. You would see a message as shown below, click on Ok, apply suggestion!
  • Enter the below two lines in build.gradle. This would add appium and cucumber-jvm under dependencies.
compile group: 'info.cukes', name: 'cucumber-java', version:
'1.2.5'
compile group: 'io.appium', name: 'java-client', version:
'5.0.0-BETA6'
  • Below is how the gradle file should look like:
      group 'com.test'

      version '1.0-SNAPSHOT'

      apply plugin: 'java'

      sourceCompatibility = 1.5
      repositories {
          mavenCentral()
      }
      dependencies {
          testCompile group: 'junit', name: 'junit', version: '4.11'


          compile group: 'info.cukes', name: 'cucumber-java', 
          version:'1.2.5'


          compile group: 'io.appium', name: 'java-client', 
          version:'5.0.0-BETA6'

      }
  • Once done, navigate to View -> Tools Window -> Gradle and click on Refresh all gradle projects icon. This would pull all the dependency in External Libraries.
  • Navigate to Preferences -> Plugins, search for cucumber for Java and click on Install (if it's not previously installed).
  • Repeat the above step for gherkin and install the same.
  • Once done restart IntelliJ, if it prompts.

We are now ready to write our first sample feature file but before that let's try to understand a brief about cucumber.

Introduction to Cucumber

Cucumber is a test framework which supports behaviour driven development (or BDD). The core idea behind BDD is a domain specific language (known as DSL), where the tests are written in normal English, expressing how the application or system has to behave. DSL is an executable test, which starts with a known state, perform some action and verify the expected state. For e.g.

  • Feature: Registration with Facebook/Google
  • Scenario: Registration Flow Validation via App

As a user I should be able to see Facebook/Google button. When I try to register myself in Quikr.

  • Given I launch the app
  • When I click on Register
  • Then I should see register with Facebook and Google

Dan North (creator of BDD) defined behaviour-driven development in 2009 as- BDD is a second-generation, outside-in, pull-based, multiple-stakeholder, multiple-scale, high-automation, agile methodology. It describes a cycle of interactions with well-defined outputs, resulting in the delivery of working, tested software that matters.

Cucumber feature files serve as a living documentation which can be implemented in many languages. It was first implemented in Ruby and later extended to Java. Some of the basic features of Cucumber are:

  • The core of cucumber is text files called feature which contains scenario. These scenarios expresses the system or application behaviour.
  • Scenario files comprise of steps which are written following the syntax of Gherkin.
  • Each step will have step implementation which is the code behind which interacts with application.

So in the above example, Feature, Scenario, Given, When, Then are keywords.

  • Feature: Cucumber tests are grouped into features. We use this name because we want engineers to describe the features that a user will be able to use.
  • Scenario: A Scenario expresses the behaviour we want, each feature contains several scenarios. Each scenario is an example of how the system should behave in a particular situation. The expected behaviour of the feature would be the total scenarios. For a feature to pass all scenarios must pass.
  • Test Runner: There are different way to run the feature file however we would be using the JUnit runner initially and then move on to gradle command for command line execution.

So I am hoping now we have a brief idea of what cucumber is. Further details can be read on their site (https://cucumber.io/). In the coming section, we will create a feature file, write a scenario, implement the code behind and execute it.

Writing first appium test

Till now we have created a sample Java project and added the appium dependency. Next we need to add a cucumber feature file and implement the code behind. Let's start that:

  • Under Project folder, create the directory structure src/test/java/features.
  • Right click on the features folder and select New -> File and enter name as Sample.feature
  • In the Sample.feature file, let's write a scenario as shown below which is about log in using Google.

    Feature: Hello World.

    Scenario: Registration Flow Validation via App.

    As a user I should be able to see my google account.

    when I try to register myself in Quikr.

    When I launch Quikr app.

    And I choose to log in using Google.

    Then I see account picker screen with my email address "testemail@gmail.com".

  • Right click on the java folder in IntelliJ, select New -> Package and enter name as steps.
  • Next step is to implement the cucumber steps, click on the first line in Sample.feature file When I launch Quikr app and press Alt+Enter, then select the option Create step definition.
  • It will present you with a pop up to enter File name, File location and File type. We need to enter below values:
    • File name: HomePageSteps
    • File Location: Browse it to the steps folder created above
    • File Type: Java

So the idea is that the steps will belong to a page and each page would typically have it's own step implementation class.

  • Once you click on OK, it will create a sample template in the HomePageSteps class file.

Now we need to implement these methods and write the code behind to launch Quikr app on emulator.

Starting appium server session and finding locators

First thing we need to do, is to download a sample app (Quikr apk in this case). Download the Quikr app (version 9.16).

  • Create a folder named app under the HelloAppium project and copy the downloaded apk under that folder.
  • Launch the appium GUI app.
  • Launch the emulator or connect your device (assuming you have Developer Options enabled).

On the appium GUI app, click on the android icon and select the below options:

  • App Path - browse to the .apk location under the app folder.
  • Platform Name - Android.
  • Automation Name - Appium.
  • Platform Version - Select the version which matches the emulator from the dropdown, it allows to edit the value.
  • Device Name - enter any string e.g. Nexus6.

Once the above settings are done, click on General Settings icon and choose the below mentioned settings. Once the setup is done, click on the icon to close the pop up.

  • Select Prelaunch application
  • Select Strict Capabilities
  • Select Override Existing Sessions
  • Select Kill Processes Using Server Port Before Launch
  • Select New Command Timeout and enter the value 7200
  • Click on Launch

This would start the appium server session. Once you click on Appium Inspector, it will install the app on emulator and launch the same.

If you click on the Record button, it will generate the boilerplate code which has Desired Capabilities respective to the run environment and app location:

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
writing-your-first-cucumber-appium-test-img-0

We can copy the above line and put into the code template generated for the step When I launch Quikr app.

This is how the code should look like after copying it in the method:

@When("^I launch Quikr app$")

public void iLaunchQuikrApp() throws Throwable {
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability("appium-version", "1.0");
    capabilities.setCapability("platformName", "Android");
    capabilities.setCapability("platformVersion", "5.1");
    capabilities.setCapability("deviceName", "Nexus6");
    capabilities.setCapability("app",     

    "/Users/nishant/Development/HelloAppium/app/quikr.apk");
    AppiumDriver wd = new AppiumDriver(new   

    URL("http://0.0.0.0:4723/wd/hub"), capabilities);
    wd.manage().timeouts().implicitlyWait(60, TimeUnit.
SECONDS
);
}

Now the above code only sets the Desired Capabilities, appium server is yet to be started. For now, we can start it from outside like terminal (or command prompt) by running the command appium.

We can close the appium inspector and stop the appium server by click in onStop on the appium GUI app.

To run the above test, we need to do the following:

  1. Start the appium server via command line (Command: appium --session-override ).
  2. In IntelliJ, right click on the feature file and choose the option to "Run...".

Now the scope of AppiumDriver is local to the method, hence we can refactor and extract appiumDriver as field.

To continue with the other steps automation, we can use the appium inspector to find the element handle. We can launch appium inspector using the above mentioned steps, then click on the element whose locator we want to find out as shown in the below mentioned screen.

writing-your-first-cucumber-appium-test-img-1

Once we have the locator, we can use the appium api (as shown below) to click it:

appiumDriver.findElement(By.id("sign_in_button")).click();

This way we can implement the remaining steps.

Write a small test for mobile web

To automate mobile web app, we don't need to install the app on the device. We need a browser and the app url which is sufficient to start the test automation. We can tweak the above written code by adding a desired capability browserName. We can write a similar scenario and make it mobile web specific:

Scenario: Registration Flow Validation via web

As a User I want to verify that

I get the option of choosing Facebook when I choose to register

When I launch Quikr mobile web

And I choose to register

Then I should see an option to register using Facebook

So the method for mobile web would look like:

@When("^I launch Quikr mobile web$")

public void iLaunchQuikrMobileWeb() throws Throwable {
    DesiredCapabilities desiredCapabilities = new     

    DesiredCapabilities();
    desiredCapabilities.setCapability("platformName", "Android");
    desiredCapabilities.setCapability("deviceName", "Nexus");
    desiredCapabilities.setCapability("browserName", "Browser");
    URL url = new URL("http://127.0.0.1:4723/wd/hub");

    appiumDriver = new AppiumDriver(url, desiredCapabilities);

    appiumDriver.get("http://m.quikr.com");
}

So in the above code, we don't need platformVersion and we need a valid value for browserName parameter.

Possible values for browserName are:

  • Chrome - For Chrome browser on Android
  • Safari - For Safari browser on iOS
  • Browser - For stock browser on Android

We can follow the same steps as above to run the test.

Finding locators in mobile web app

To implement the remaining steps of above mentioned feature, we need to find locators for the elements we want to interact with. Once the locators are found then we need to perform the desired operation which could be click, send keys etc.

Below mentioned are the steps which will help us find the locators for a mobile web app:

  • Launch the chrome browser on your machine and navigate to the mobile site (in our case:  http://m.quikr.com)
  • Select More Tools -> Developer Tools from the Chrome Menu
  • In the Developer Tool menu items, click on the Toggle device toolbar icon.
writing-your-first-cucumber-appium-test-img-2
  • Once done the page would be displayed in a mobile layout format.
  • In order to find the locator of any UI element, click on the first icon of the dev tool bar and then click on the desired element.
  • The HTML in the dev tool layout would change to highlight the selected element. Refer the below screenshot which shows the same.
writing-your-first-cucumber-appium-test-img-3
  • In the highlight panel on the right side, we can see the following properties name=query and id=query . We can choose to use id and implement the step as:
appiumDriver.findElement(By.id("query")).click();

Using the above way, we can find the locator of the various elements we need to interact with and proceed with our test automation.

Summary

So in this article, we briefly described how we would go about writing test for a native app as well as a mobile web. We discussed how to create a project in IntelliJ and write a sample feature file. We also learned how to start the appium inspector and look for locator. We learned about the chrome dev tool and how can use the same to find locator for mobile web.

Resources for Article:


Further resources on this subject: