How to write Appium testing code-your complete guide 2020

Appium Testing Tutorial
Appium Testing Tutorial

We will discuss how to write  Appium testing scripts in this tutorial. We can test our applications on Simulator and real devices. Appium supports both Android and iOS platforms.

Topics Covered :

How to find app package and activity in android

To run your Appium testing scripts in Android devices, we have to pass app package and app activity as desired capabilities. There are a couple of ways to get the app activity and app package. We will discuss these here. For this example, we will choose the contact app. Please follow the below steps to get the activity and app package.

For Windows

  • Type “adb devices” to check attached devices or emulator
  • Once your device is attached tap on contact app to open it.
  • Please type below commands to get the app activity and package
adb shell dumpsys window 
| find -E mCurrentFocus

For Mac/Linux

  • Type “adb devices” to check attached devices or emulator
  • Once your device is attached tap on contact app to open it.
  • Please type below commands to get the app activity and package
adb shell dumpsys window 
| grep mCurrentFocus
How to Add App package/activity
How to Add App package/activity

How to create your first project for Appium testing

To create the Appium Testing project, we need Maven, TestNG, and Appium Java, clients. We will discuss this in detail below.

Prerequisite

  • Maven
  • Add TestNG as a maven dependency
  • Add Appium java client

How to create a Maven project

To create a maven project for Appium testing, please click on File and choose New–> Project.

Creating a project in IntelliJ
Creating a project

After that, please select Maven and click on Next

Choose maven and click on next
Choose Maven and click on next

It will ask for Groupid and Artifactid. Please provide the same. Please check the below image for reference.

maven artifact id,group id
provide groupId, Artifact id for Maven

Now select the Project Name and click on Finish.

Project Name
Add Project Name
How to add maven dependency
How to add Maven dependency

We have to add the testNG dependency in the pom.xml for verifying your application. Please add below dependencies in your pom.xml as shown in the above image.

<dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8.5</version>
            <scope>test</scope>
        </dependency>
      
        <dependency>
            <groupId>io.appium</groupId>
            <artifactId>java-client</artifactId>
            <version>7.2.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Desired Capabilities Appium testing

In Appium testing, we need the desired capabilities to interact with devices. Desired Capabilities are parameters sent as a key-value pair encoded in a JSON format to interact with Android/iOS devices. Appium clients send this information to the Appium server when a new session starts. Each Appium client builds capabilities in their way. But ultimately, all the parameters will be sent in a JSON format to the server. For more details on Desired Capabilities, click this link.

How to add desired capabilities for Android

To interact with your Android devices with your Appium server, we have to pass specific desired capabilities. It will help the Appium server to identify the attached Android devices uniquely. Below are the lists:

1. You have to pass the key as “platformName” or “MobileCapabilityType.PLATFORM_NAME” and value as “android

2. You have to pass the key as “platformVersion” or “MobileCapabilityType.PLATFORM_VERSION” and value as “23” [this value is the api version of the android version]

3. You have to pass the key as “deviceName” or “MobileCapabilityType.DEVICE_NAME” and value as “Nexus 5X“[ please update the value with your device name]

4. You have to pass the key as “automationName” or “MobileCapabilityType.AUTOMATION_NAME” and value as “UIAutomator2“[ you have to use UIAutomator if UIAutomator2 does not work]

5. You have to pass the key as “udid” or “MobileCapabilityType.UDID” and value as “emulator-5554

6. You have to pass the key as “appPackage” and value as “com.android.contacts“[ update app packages of your app]

7. You have to pass the key as “appActivity” and value as “com.android.contacts.activities.PeopleActivity” [ update app activity of your app]

8. Please refer below image for details:

Adding desired capabilities for Android
Adding desired capabilities for Android

How to add desired capabilities for iPhone

To interact with your Android devices with your Appium server, we have to pass specific desired capabilities. It will help the Appium server to identify the attached Android devices uniquely. Below are the lists:

1. You have to pass the key as “platformName” or “MobileCapabilityType.PLATFORM_NAME” and value as “iOS

2. You have to pass the key as “platformVersion” or “MobileCapabilityType.PLATFORM_VERSION” and value as “13.6” [please check your os version]

3. You have to pass the key as “deviceName” or “MobileCapabilityType.DEVICE_NAME” and value as “iPhone 11 Pro Max“[ please update the value with your device name]

4. You have to pass the key as “automationName” or “MobileCapabilityType.AUTOMATION_NAME” and value as “XCUITest“[ use XCUITest(iOS 9.3 and above) or UIAutomation(iOS 9.3 and lower)]

5. You have to pass the key as “udid” or “MobileCapabilityType.UDID” and value as “3C4B567E-C4E4-445D-A613-F4867DD2FF67“[ update with your device id]

6. Please refer below image for details:

Adding desired capabilities for iOS
Adding desired capabilities for iOS

How to write an Appium testing script(Android)

  1. To write your first Appium testing script, at first, we need to get the device id of the attached android devices or emulator. To get the device id, open your terminal or command prompt and type “adb devices.” It will show the list of devices.
  2. After that, we need to create a java class. To create a java class, please go to the “/src/main/java/” folder in your IDE, right-click on that and choose new –> Java Class.
  3. Now we will add a setup method under BeforeTest and create an instance of AndroidDriver.
  4. We have to add the desired capabilities shown above to set the device parameters.
  5. We will now create a URL with hub details where the Appium is running.
  6. Now we will call the AndroidDriver constructor and pass the URL and desired capabilities to initialize the driver.
  7. In the Test method, we will perform the actions and assert the desired results. To know how to inspect the element on the iPhoneplease refer to this link. To learn about the Appium methodsplease click here.
  8. We have provided a sample code below for reference. Please go through that.
  9. In the AfterTest method, we will quit the driver to close the current session.

How to create a Java Class for Appium testing

To create a java class, please see the below image:

How to create a java class
How to create a java class

Sample Appium testing code in Android

import io.appium.java_client.MobileElement;
import io.appium.java_client.android
        .AndroidDriver;
import io.appium.java_client.remote
        .MobileCapabilityType;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote
        .DesiredCapabilities;
import org.openqa.selenium.support
        .ui.ExpectedConditions;
import org.openqa.selenium.support
        .ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class RunFirstTestAndroid {
    private AndroidDriver driver;

    @BeforeTest
    public void setup() throws MalformedURLException {
        DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
        desiredCapabilities
                .setCapability
                        ("platformName", "Android");
        //desiredCapabilities
        // .setCapability(MobileCapabilityType
        // .PLATFORM_NAME, "Android");
        desiredCapabilities
                .setCapability
                        ("platformVersion", "23");
        //desiredCapabilities
        // .setCapability(MobileCapabilityType
        // .PLATFORM_VERSION, "23");
        desiredCapabilities
                .setCapability
                        ("deviceName", "Nexus 5X");
        //desiredCapabilities
        // .setCapability(MobileCapabilityType
        // .DEVICE_NAME, "Nexus 5X");
        desiredCapabilities
                .setCapability
                        ("automationName", "UIAutomator2");
        desiredCapabilities
                .setCapability
                        (MobileCapabilityType.UDID, "emulator-5554");
        desiredCapabilities
                .setCapability
                        ("udid", "emulator-5554");
        desiredCapabilities
                .setCapability(
                        "ensureWebviewsHavePages", true);
        desiredCapabilities
                .setCapability
                        ("appPackage", "com.android.contacts");
        //desiredCapabilities
        // .setCapability(MobileCapabilityType
        // .App, "com.android.contacts");
        desiredCapabilities
                .setCapability
                        ("appActivity",
                                "com.android.contacts" +
                                        ".activities.PeopleActivity");

        URL remoteUrl = new URL("http://127.0.0.1:4723/wd/hub");
        driver = new AndroidDriver(remoteUrl, desiredCapabilities);
        driver.manage().timeouts()
                .implicitlyWait(20, TimeUnit.SECONDS);
    }

    @Test
    public void sampleTest() throws InterruptedException {
        //Adding new contact
        driver.findElementByAccessibilityId
                ("add new contact")
                .click();
        //clicking on OK button
        WebElement element=driver
                .findElementById
                        ("com.android.contacts" +
                                ":id/right_button");
        element.click();
        //Updating the firstname
        driver.findElementByXPath(
                "/hierarchy/android.widget." +
                "FrameLayout/android.view" +
                        ".ViewGroup/android.widget" +
                ".FrameLayout[2]/android" +
                        ".widget.FrameLayout/android.widget" +
                ".ScrollView/android.widget" +
                        ".LinearLayout/android.widget" +
                ".LinearLayout[2]/android.widget" +
                        ".LinearLayout/android.widget" +
                ".LinearLayout/android.widget" +
                        ".LinearLayout/" +
                        "android.widget.EditText")
                .sendKeys("Hello");
        //updating phone number
        driver
                .findElementByXPath("//android.widget" +
                        ".EditText[@text='Phone']")
                .sendKeys("1234567890");
        //updating email id
        driver
                .findElementByXPath("//android.widget" +
                        ".EditText[@text='Email']")
                .sendKeys("xyz@gmail.com");
        //save the contact
        driver
                .findElementById("com.android" +
                        ".contacts" +
                        ":id/menu_save")
                .click();
        WebDriverWait wait=new WebDriverWait(driver,30);
        WebElement el=driver
                .findElementByXPath("//android.view" +
                        ".View[@content-desc=\"Hello\"]");

        wait.until(ExpectedConditions
                .visibilityOfAllElements(el));

        Assert.assertEquals(el
                .getAttribute("content-desc"),"Hello");
        Assert.assertEquals(driver
                .findElementByXPath("\t\n" +
                "//android.widget" +
                        ".RelativeLayout[@content-desc=" +
                        "\"Call Mobile 1 234-567-890\"]" +
                "/android.widget.TextView[1]")
                .getText(),"1 234-567-890");
        Assert.assertEquals(driver.
                findElementByXPath("//android.widget" +
                        ".RelativeLayout[@content-desc" +
                        "=\"Email Home xyz@gmail.com\"]" +
                        "/android.widget.TextView[1]\n")
                .getText(),"xyz@gmail.com");

    }



    @AfterTest
    public void tearDown(){
        driver.quit();
    }
}


How to write an Appium testing script in iPhone

  1. To write your first Appium testing script, at first, we need to get the device id of the attached iPhone devices or Simulator. To get the device id, open your terminal type “xcrun simctl list | egrep ‘(Booted).’ ” It will show the list of devices. Please refer to this link for more information.
  2. After that, we need to create a java class. To create a java class, please go to the “/src/main/java/” folder in your IDE, right-click on that and choose new –> Java Class.
  3. Now we will add a setup method under BeforeTest and create an instance of IOSDriver.
  4. We have to add the desired capabilities shown above to set the device parameters.
  5. We will now create a URL with hub details where the Appium is running.
  6. Now we will call the IOSDriver constructor and pass the URL and desired capabilities to initialize the driver.
  7. In the Test method, we will perform the actions and assert the desired results. To know how to inspect the element on the iPhoneplease refer to this link. To learn about the Appium methodsplease click here
  8. We have provided a sample code below for reference. Please go through that.
  9. In the AfterTest method, we will quit the driver to close the current session.

Sample Appium testing code for iPhone

import io.appium.java_client.MobileElement;
import io.appium.java_client.ios.IOSDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote
.DesiredCapabilities;
import org.openqa.selenium.support
.ui.ExpectedConditions;
import org.openqa.selenium.support
.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class RunFirstiOSTest {
    private IOSDriver driver;

    @BeforeClass
    DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
        desiredCapabilities
                .setCapability("platformName", "iOS");
        desiredCapabilities
                .setCapability("platformVersion", "13.6");
        desiredCapabilities
                .setCapability("deviceName", "iPhone 11 Pro Max");
        desiredCapabilities
                .setCapability("automationName", "XCUITest");
        desiredCapabilities
                .setCapability("udid", "3C4B567E-C4E4-445D-A613-F4867DD2FF67");
        URL remoteUrl = new URL("http://127.0.0.1:4723/wd/hub");

        driver = new IOSDriver(remoteUrl, desiredCapabilities);
        driver.manage().timeouts()
                .implicitlyWait(20, TimeUnit.SECONDS);
    }

    @Test
    public void sampleTest() {
        //Clciking on the contact app
        MobileElement el1 = (MobileElement) driver
                .findElementByAccessibilityId
                        ("Contacts");
        el1.click();
        //Clicking on Add contact
        MobileElement el2 = (MobileElement) driver
                .findElementByAccessibilityId
                        ("Add");
        el2.click();
        //Sending value to the First Name
        MobileElement el3 = (MobileElement) driver
                .findElementByAccessibilityId
                        ("First name");
        el3.sendKeys("Name1");
        //Sending value to the Last Name
        driver.findElementByAccessibilityId
                ("Last name")
                .sendKeys("Surname");
        //Sending value to the Company
        driver
                .findElementByAccessibilityId
                        ("Company")
                .sendKeys("xyz");
        //Clicking on home
        driver
                .findElementByXPath
                        ("//XCUIElementTypeCell[@name=\"add phone\"]")
                .click();
        //Exmaple of explicit wait. Waiting for the element to be visible
        WebDriverWait wait=new WebDriverWait(driver,30);

        WebElement el= driver
                .findElementByXPath
                        ("//XCUIElementTypeTextField" +
                                "[@name=\"home\"]");
        wait.until(ExpectedConditions
                .visibilityOfAllElements(el));
        el.sendKeys("1234567890");
        //Clcking on Done
        driver
                .findElementByXPath(
                        "//XCUIElementTypeButton" +
                        "[@name=\"Done\"]")
                .click();
        //Asserting the value to verify
        Assert.assertEquals(driver
                .findElementByXPath(
                        "//XCUIElementTypeStaticText" +
                        "[@name=\"Name1 Surname\"]\n")
                .getText(),"Name1 Surname");
        Assert.assertEquals(driver
                .findElementByXPath(
                        "//XCUIElementTypeStaticText" +
                        "[@name=\"xyz\"]")
                .getText(),"xyz");
       
    }

    @AfterClass
    public void tearDown() {
        //Quiting the driver
       driver.quit();
    }



}

testNG Assert

In the above code, we have used testNG Assert to verify the expected data with the actual data we are getting from the elements using getText() or getAttributes methods. Assert helps us make the test case Pass if the conditions satisfy; otherwise, it fails the test case.

Conclusion

Till now, we have covered how to write your first Appium testing scripts in Android and iOShow to use Desired Capabilities, how to create a maven project. In the next session, we will discuss Appium Testing Questions and Answers. For a full tutorial on Appium, you can click here

Reference

  1. Maven
  2. TestNG

About Himadri Das

Hi, I am Himadri Das, I am a blogger, and an open source contributor. I have about 11 years of experience in the Information Technology domain. Currently I am working in a Startup Company as Quality Assurance Manager. I have hands-on experience on Appium, Selenium, QTP, Locust, Automation framework, Performance Testing, Functional Testing, Java, python, Shell scripting, MySql, Redis, Kafka etc. Apart from my work and writing blogs, I love to play guitar, love to travel and love to watch cricket and football. If you want to know more about me, please visit my linkedin profile - https://www.linkedin.com/in/himadri-das-2b6b7421/.