You are on page 1of 17

Appium mobile test automation

for Google Android and Apple iOS

Last updated: 29 September 2017

© Pepgo Limited, 71-75 Shelton Street, Covent Garden, London, WC2H 9JQ, United Kingdom
Contents
About this document .............................................................................................................................. 3
Appium .................................................................................................................................................... 3
Architecture ............................................................................................................................................ 3
Enable developer options on an Android device: ................................................................................... 4
Install Android Studio and SDK (in Microsoft Windows) ........................................................................ 5
Install Appium: ........................................................................................................................................ 5
Run Appium (example) ........................................................................................................................... 5
Create an Android Virtual Device ........................................................................................................... 7
Installing an app on a Virtual Device....................................................................................................... 8
Finding element properties .................................................................................................................... 9
Using “Appium Desktop” .................................................................................................................... 9
Using “UI Automator Viewer” ............................................................................................................. 9
Using Appium Inspector .................................................................................................................... 10
Remote debugging Android hybrid applications with Google Chrome ............................................ 11
A full Appium Java example .................................................................................................................. 11
What the PasswdSafe example does ................................................................................................ 11
Using the PasswdSafe example......................................................................................................... 12
The “pom.xml” file ............................................................................................................................ 13
The “AppiumTest.java” file ............................................................................................................... 13
The “AndroidSetup.java” file ............................................................................................................ 14
The “LandingPage.java” file .............................................................................................................. 15
The “BasePage.java” file ................................................................................................................... 16
About this document
This document explains the test automation tool Appium for mobile devices. Appium is powered by
Selenium WebDriver, and the same Appium program code can be used for automating both Google
Android and Apple iOS platforms.

This document contains Java samples developed on the Microsoft Windows operating system for
Google Android as target platform. The samples in this document use an Android native app, but
they can easily be adapted to Android hybrid applications, or Android mobile web applications.

The examples can also easily be adapted for development on the Apple macOS operating system,
targeting the Apple iOS mobile platform for mobile devices such as the Apple iPhone.

Appium
Appium is an open source test automation tool for mobile applications. It allows you to test all the
three types of mobile applications: native, hybrid and mobile web.

It also allows you to run the automated tests on actual devices, emulators and simulators.

Today when almost every mobile app is available for at least two platforms (iOS and Android), you
need a tool, which allows testing cross platforms. Having two different frameworks for the same app
would increase the cost of testing and time to maintain it as well.

The basic philosophy of Appium is that you should be able to reuse code between iOS and Android,
and that’s why the API’s are the same across iOS and Android. Another important thing to highlight
is that unlike Calabash, Appium doesn’t modify your app or need you to even recompile the app, or
have access to its source code.

Appium lets you choose the language you want to write your test in. It doesn’t dictate the language
or framework to be used.

Architecture
When you download Appium, you are basically downloading the server. The server is written in
Node.js and implements Selenium WebDriver. It allows you to use Selenium WebDriver clients to
drive your tests. Your mobile app acts precisely like a web app, where the DOM is represented by
the View hierarchy.

So this server basically exposes a REST API, which performs the following actions:

1. Receives connection from client


2. Listen command
3. Execute command
4. Respond back the command execution status
In terms of an architecture diagram, this is how Appium can be explained:

Enable developer options on an Android device:


This article contains helpful background information:
http://www.greenbot.com/article/2457986/how-to-enable-developer-options-on-your-android-
phone-or-tablet.html

1. On stock Android go to: “Settings > About phone > Build number”.
2. Once you’ve found the build number section of the settings, tap on the section 7 times. After
two taps, a small pop up notification should appear saying "you are now X steps away from
being a developer" with a number that counts down with every additional tap. After the 7th
tap, the developer options will be unlocked and available. They can usually be found in the
main settings menu.
3. Switch on "Stay awake".
4. Switch on "USB debugging".

To check if the (real) device can be used, type from command prompt: "adb devices" (after you
have correctly installed the Android SDK, as described in the next paragraph). In Microsoft Windows,
the output should look like this:

C:\>adb devices
List of devices attached
00c600c600c600c6 device

If the device is not recognised, then check if the USB driver is correctly installed in Microsoft
Windows: http://developer.android.com/studio/run/oem-usb.html
Install Android Studio and SDK (in Microsoft Windows)
Android Studio contains the Android SDK. It is recommended to install Android Studio, although you
can also just install the Android SDK (the links to the SDK are provided at the bottom of the page
under “Get just the command line tools”).

1. Go to https://developer.android.com/studio/index.html
2. Download Android Studio
3. Confirm the license agreement
4. Launch the downloaded “*.exe” file
5. Follow the setup wizard to install Android Studio and the SDK

Install Appium:
Appium can be downloaded from http://appium.io/downloads.html

Run Appium (example)


The following example uses the open source “Password Safe” app ( https://www.pwsafe.org/ ). The
app is available for free from the “Google play” app store. The source code, including the “*.apk”
file for this app are available from http://sourceforge.net/projects/passwdsafe/ (just click on the
“Download” link).

The Android app file (“*.apk”) must be set in the “Application Path” of the Appium Android
Settings. However, please note that some versions of Appium have problems with paths that contain
spaces, so avoid that if possible.

Newer versions of Appium will find the Package and (starting) activity automatically, but if not, then
theses can also be found from command line with the command:

aapt dump badging PasswdSafe.apk

Note that “aapt” is part of the Android SDK “build-tools” folder (in the relevant Android SDK
version subfolder). So if the command is not recognised, then you might have to add the folder to
your Microsoft Windows “path” environment variable.
Under “Device Name”, you will have to set the (real or virtual) device name that you know from
running the “adb devices” command.

In the “General Settings”, it is recommended to tick the “Pre-Launch Application” option:


Once the Appium server is started, you will see some logs in the Appium screen, or alternately check
this local URL for the status of the Appium server:

http://localhost:4723/wd/hub/status

Create an Android Virtual Device


Many developers prefer working with real devices, as the Google virtual devices are notoriously slow
and often painful to create and use. However, it is still often required to create and use virtual
devices, particularly to cover the wide range of Android devices both with respect to device
hardware and screen sizes, as well as Android versions.

You first need to open the Android Virtual Device Manager. From a command prompt, you can do
this with the command “android avd”.

Then you need to create an Android Virtual Device. The ideal settings for the device depend on the
host machine. Here are a few performance tips for Microsoft Windows:
1. If you run on a host machine with an Intel processor that supports Intel’s virtualisation (VT-x)
technology, then use “Intel Atom (x86)” as CPU/ABI. Please note that you therefore need to
install HAXM ("Intel Hardware Accelerated Execution Manager") through the Android SDK
Manager.
2. A lower screen resolution is generally faster, for example use “WVGA800”.
3. If you tick the “Snapshot” option, then you will be able to save a snapshot of the machine
and therefore be much faster on the next start/execution.

You can start virtual devices right from the Android Virtual Device Manager by selecting the device
and clicking the “Start…” button.

As you already know, you can check the name(s) of the running virtual and real devices from
command line:
“adb devices”

Installing an app on a Virtual Device


Once your Virtual Device is ready, you can install an app on the Virtual Device.

The first step is to run the Virtual Device, on which you want to install the app. You can start a
Virtual Device from the AVD Manager by clicking the “Start…” button, or from the command line:
emulator -avd <AVD_Name>

This launches the Virtual Device and the command is running in the command prompt window.
Launch another command prompt window and run the following command (the parameter “–e” is
for specifically addressing the Emulator, for addressing a real device on a USB connection, the
corresponding parameter is “–d”).
adb –e install <path_to_apk_file>
Finding element properties
Using “Appium Desktop”
Appium Desktop is an open source app for Mac, Windows, and Linux that presents the power of the
Appium automation server in a beautiful and flexible UI. It is a combination of a few Appium-related
tools: Being a graphical interface for the Appium server, it is an excellent tool for finding locators
required for Page Objects.

https://github.com/appium/appium-desktop/releases

Appium Desktop integrates with the Android Debug Bridge (ADB), which is useful for querying
devices to get hold of package names.

https://developer.android.com/studio/command-line/adb

Using “UI Automator Viewer”


“uiautomatorviewer” is an application that comes packaged with the Android SDK and is
present under the “tools” folder of the Android SDK. It is a tool that lets you inspect the User
Interface (UI) of an application in order to explore the layout hierarchy, and view the properties
associated with the controls.

While writing your tests, this tool is essential, as it exposes the Id and other attributes of an element,
which are required for writing scripts.

Clicking on the devices icon (second from the left, next to the open folder icon) takes a dump of a UI
XML snapshot of the screen shown on the device.

The left side of the tool shows how the device looks like. The right side is divided in two parts:

1. The upper half shows the UI XML snapshot and the nodes structure.
2. The lower half shows the details of the selected node with all the attributes.
You can explore the properties of UI elements by clicking on them. Usually, the most helpful
property for scripting is the “resource-id”, but it is not always available. When it is not available, it is
often best to use the class name in combination with another property (such as text) to generate an
Xpath expression that uniquely identifies the UI element.

Using Appium Inspector


An alternative tool to the “uiautomatorviewer” is the “Appium Inspector” that is available
from the Appium toolbar of the Appium server:
Remote debugging Android hybrid applications with Google Chrome
When working with Android hybrid applications (as opposed to Android native apps), then the
Google Chrome web browser offers better and faster locator features than the
“uiautomatorviewer”. However, it requires a real device connected through a USB cable to the
machine with the Google Chrome web browser.

A full Appium Java example


The Android app “PasswdSafe” is a port of the popular free and open-source password manager
program “Password Safe” to Android. Password Safe allows you to safely and easily create a secured
and encrypted user name/password list. With Password Safe all you have to do is to create and
remember a single "Master Password" of your choice in order to unlock and access your entire user
name/password list.

PasswdSafe supports viewing and editing of Password Safe data files. You can therefore exchange
your data files between your (Microsoft Windows) PC and your Android device.

The PasswdSafe app can be installed on your Android device from Google play.

The app and the source code can also be downloaded from
http://sourceforge.net/projects/passwdsafe/ .

What the PasswdSafe example does


The PasswdSafe example project will first create an empty password file and then delete the newly
create file. Here are some screenshots from an Android phone device:
Using the PasswdSafe example
You need to download the ZIP-file with the source code from
http://sourceforge.net/projects/passwdsafe/ and place the “PasswdSafe.apk” file in the “apps”
folder of your Java project:

The other 5 required files are:

File name Contains

pom.xml Contains information about the project and configuration details


used by Apache Maven to build the project.
AppiumTest.java Contains the test(s). This example project only contains one single
test case (with the JUnit annotation “@Test”). Most “real world”
projects would contain multiple test cases.
AndroidSetup.java Contains the initialisation information for the Selenium (Appium)
web driver.
BasePage.java A library that contains generally useful universal helper methods.
Not all of them are used in this example project.
LandingPage.java Contains methods for the landing page of the application. It extends
the selection of the general purpose methods defined in
“BasePage.java”.
This project contains one method for creating files, and one
method for deleting files.
In most “real world” applications, there will be multiple pages, each
with specific methods for a particular page.

The “pom.xml” file


This example projects targets Java version 8 (1.8) in its Apache Maven “pom.xml” file. You might
have to adapt the “pom.xml” file to fit your environment and change the version numbers of the
dependencies:

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pepgo</groupId>
<artifactId>AppiumPasswdSafe</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>4.1.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

The “AppiumTest.java” file


“@BeforeClass” prepares the Selenium WebDriver, while “@AfterClass” disposes the driver.
In between the two, all “@Test” will be executed, although this example only contains one single
test.

package com.pepgo.appiumpasswdsafe.scenarios;

import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.openqa.selenium.By;

import com.pepgo.appiumpasswdsafe.pages.LandingPage;

public class AppiumTest extends AndroidSetup {

@BeforeClass
public static void setUp() throws Exception {
prepareAndroidForAppium();
}

@AfterClass
public static void tearDown() throws Exception {
driver.quit();
}

@Test
public void createAndDeletePasswdSafeFile_Test() throws Exception {
// Close start pop-up window
driver.findElement(By.id("android:id/button1")).click();

// Create new PasswdSafe file


new LandingPage(driver).createPasswdSafeFile("MyFileName", "MyPassword");

// Delete new PasswdSafe file


new LandingPage(driver).deletePasswdSafeFile("MyFileName", "MyPassword");
}
}

The “AndroidSetup.java” file


This setup executes the tests on a (virtual or real) device called “00c600c600c600c6”. You will have
to adapt this to fit your environment. You must also adapt the application path to the “apps” folder
where you have saved the “PasswdSafe.apk” file.

package com.pepgo.appiumpasswdsafe.scenarios;

import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

public class AndroidSetup {

protected static AndroidDriver driver;

protected static void prepareAndroidForAppium() throws MalformedURLException {


File appDir = new File("C:\\Temp\\apps");
File app = new File(appDir, "PasswdSafe.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("device","Android");
capabilities.setCapability("deviceName","00c600c600c600c6");
capabilities.setCapability("platformName","Android");

//other caps
capabilities.setCapability("app", app.getAbsolutePath());
driver = new AndroidDriver(new URL("http://localhost:4723/wd/hub"), capabilities);
}
}

The “LandingPage.java” file


This Java class contains the methods that are available for the main page of the app. The class
extends the general purpose helper functions of the “BasePage.java” class.
package com.pepgo.appiumpasswdsafe.pages;

import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
import static org.junit.Assert.*;

public class LandingPage extends BasePage {

public LandingPage(AndroidDriver driver) {


super(driver);
}

public LandingPage createPasswdSafeFile(String strFileName, String strPassword) {

By menuFileNew = By.id(app_package_name + "menu_file_new");


By editTextFileName = By.id(app_package_name + "file_name");
By editTextPassword = By.id(app_package_name + "password");
By editTextPasswordConfirm = By.id(app_package_name + "password_confirm");

// Create new file


driver.findElement(menuFileNew).click();

// Enter file name


driver.findElement(editTextFileName).sendKeys(strFileName);

// Enter password
driver.findElement(editTextPassword).click();
enterTextInPasswordField(strPassword);

// Enter password confirmation


driver.findElement(editTextPasswordConfirm).click();
enterTextInPasswordField(strPassword);

// Click OK
driver.findElement(By.id("android:id/button1")).click();

// Click widget button


driver.findElement(By.className("android.widget.ImageButton")).click();

// Click on text "Close"


driver.findElement(By.xpath("//android.widget.TextView[@text='Close']")).click();

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

// Assert that the PasswdSafe file exists


assertTrue(driver.findElements(By.xpath("//android.widget.TextView[@text='" +strFileName+ ".psafe3']")).size() > 0);

return new LandingPage(driver);


}

public LandingPage deletePasswdSafeFile(String strFileName, String strPassword) {

By enterTextPassword = By.id(app_package_name + "passwd_edit");


By checkboxConfirm = By.id(app_package_name + "confirm");

// Click on text for file name


driver.findElement(By.xpath("//android.widget.TextView[@text='" + strFileName + ".psafe3']")).click();

// Enter password
driver.findElement(enterTextPassword).click();
enterTextInPasswordField(strPassword);
// Click widget button
driver.findElement(By.className("android.widget.ImageButton")).click();

// Click on text "File Operations…"


driver.findElement(By.xpath("//android.widget.TextView[@text='File Operations…']")).click();

// Click on text "Delete File"


driver.findElement(By.xpath("//android.widget.TextView[@text='Delete File']")).click();

// Click on checkbox "Confirm"


driver.findElement(checkboxConfirm).click();

// Click OK
driver.findElement(By.id("android:id/button1")).click();

// Assert that the PasswdSafe file no longer exists


assertEquals(driver.findElements(By.xpath("//android.widget.TextView[@text='" +strFileName+ ".psafe3']")).size(), 0);

return new LandingPage(driver);


}
}

The “BasePage.java” file


This Java class contains useful general purpose helper functions.
package com.pepgo.appiumpasswdsafe.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.HashMap;

public class BasePage {

protected static AndroidDriver driver;


String app_package_name = "com.jefftharris.passwdsafe:id/";

public BasePage(AndroidDriver driver) {


this.driver = driver;
}

protected void waitForVisibilityOf(By locator) {


WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
}

protected void waitForClickabilityOf(By locator) {


WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(locator));
}

public void scrollPageUp() {


JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, Double> swipeObject = new HashMap<String, Double>();
swipeObject.put("startX", 0.50);
swipeObject.put("startY", 0.95);
swipeObject.put("endX", 0.50);
swipeObject.put("endY", 0.01);
swipeObject.put("duration", 3.0);
js.executeScript("mobile: swipe", swipeObject);
}

public void swipeLeftToRight() {


JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, Double> swipeObject = new HashMap<String, Double>();
swipeObject.put("startX", 0.01);
swipeObject.put("startY", 0.5);
swipeObject.put("endX", 0.9);
swipeObject.put("endY", 0.6);
swipeObject.put("duration", 3.0);
js.executeScript("mobile: swipe", swipeObject);
}

public void swipeRightToLeft() {


JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, Double> swipeObject = new HashMap<String, Double>();
swipeObject.put("startX", 0.9);
swipeObject.put("startY", 0.5);
swipeObject.put("endX", 0.01);
swipeObject.put("endY", 0.5);
swipeObject.put("duration", 3.0);
js.executeScript("mobile: swipe", swipeObject);
}

public void swipeFirstCarouselFromRightToLeft() {


JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, Double> swipeObject = new HashMap<String, Double>();
swipeObject.put("startX", 0.9);
swipeObject.put("startY", 0.2);
swipeObject.put("endX", 0.01);
swipeObject.put("endY", 0.2);
swipeObject.put("duration", 3.0);
js.executeScript("mobile: swipe", swipeObject);
}

public void performTapAction(WebElement elementToTap) {


JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, Double> tapObject = new HashMap<String, Double>();
tapObject.put("x", (double) 360); // in pixels from left
tapObject.put("y", (double) 170); // in pixels from top
tapObject.put("element", Double.valueOf(((RemoteWebElement) elementToTap).getId()));
js.executeScript("mobile: tap", tapObject);
}

// Accepts only numbers (key codes 7-16) and lower and upper case letters (key codes 29-54)
// Key code 66 is <Enter>
public void enterTextInPasswordField(String strTextToEnter) {
int intCounter, intKey;
for (intCounter = 0; intCounter < strTextToEnter.length(); intCounter++) {
intKey = (int) strTextToEnter.charAt(intCounter);
if (intKey > 47 && intKey < 58) {
intKey = intKey - 41;
driver.pressKeyCode(intKey);
}
else if (intKey > 64 && intKey < 91) {
intKey = intKey - 36;
driver.pressKeyCode(intKey, 1);
}
else if (intKey > 96 && intKey < 123) {
intKey = intKey - 68;
driver.pressKeyCode(intKey);
}
}
driver.pressKeyCode(66);
}
}

You might also like