Appium For Android
Appium For Android
of Contents
Introduction 1.1
Introduction to Mobile Test Automation 1.2
What is Appium 1.3
Appium 1.6.0 1.4
System Installation 1.5
Installing Android 1.5.1
Installing Appium via app 1.5.2
Installing App on Emulator 1.5.3
Install Appium via npm 1.5.4
Writing First Android Test 1.6
Java - Gradle Project 1.6.1
Understanding Desired Capabilities 1.6.2
Desired Capabilities for Android 1.6.3
Exploring UiAutomatorViewer 1.7
Exploring Appium Inspector 1.8
Remote Debugging on Android via Chrome 1.9
Starting Appium Server 1.10
Executing Test on Real Devices 1.11
Working with Genymotion Emulator 1.12
Automating Gestures 1.13
Tips (With Code Snippets) 1.14
Running multiple Appium Server for parallel execution 1.15
References 1.16
2
Introduction
Introduction
Appium is an Open Source tool for testing native or hybrid mobile apps. It uses WebDriver
JSON Wire protocol to drive both iOS and Android apps.
This book is an effort in the direction of consolidating all the knowledge and resources
around appium. It will help software developers and testers successfully use Appium to
automate the Android application.
This book will take you through the journey of understanding appium. It would also help you
understand how the different pieces come together to build a test automation framework for
Android App testing.
Book also contains lot of code snippets which will help you in your daily automation
stuff to get you started with Appium and Java.
This book also contains a git link to an android project which could be ported for any other
android application automation with basic alteration.
3
Introduction
This is a java project which has been created using IntelliJ IDea Community Edition. POM
File manages the dependency of Selenium. Project is using TestNG annotation. We have
also bundled the respective android mobile application under the apps folder for ease.
affordable,
niche
rapid
Happy Reading!!!
4
Introduction to Mobile Test Automation
While in this book we are not going to discuss all of these but look into one aspect of the
challenge which is "lack of easy to use api". Appium is very popular because of api's which
are similar to that of Selenium.
All the instructions mentioned here after are tested on Mac OSX version (10.10).
5
What is Appium
What is 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 every mobile app is made in at least two platform iOS and Android, you for sure
need a tool, which allows testing cross platform. Having two different frameworks for the
same app increases the cost of the product 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 thats why when you see the API they are same across iOS and android.
Another important thing to highlight here is that unlike Calabash, Appium doesnt modify
your app or need you to even recompile the app.
Appium lets you choose the language you want to write your test in. It doesnt dictate the
language or framework to be used.
Architecture
So how does Appium do all this? Lets try to understand what happens behind the scenes.
When you download the Appium app you are basically downloading the server. The server is
written in Node.js and implements the Selenium WebDriver. It allows one to use available
WebDriver client to fire your tests. And then your mobile app acts precisely like a web app
where the DOM is represented by View hierarchy.
So this server basically exposes REST api which performs the following actions:
6
What is Appium
7
Appium 1.6.0
UiAutomator 2
With release of appium 1.6.0 , appium has started using UiAutomator 2
Till now appium was primarily dependent on Google's UiAutomator framework as the
primary way of automating native Android apps.
automationName: uiautomator2
Prerequisites: This module should support from Android 5.0 (API Level 20) and above
For more info, check out the wiki article here: https://github.com/appium/appium-
uiautomator2-server/wiki
XCUITest
Appium has added support for Apple's new XCUITest framework. When you specify a
platformVersion of 10 or higher in Capabilities Builder, Appium automatically uses the
XCUITest automation backend.
If you want to run your iOS test on version 9.3, then you need to specify
automationName: XCUITest
8
System Installation
Installing Appium
Continuing from the last chapter, which was more to explain what Appium is about and the
explanation of architecture. This chapter will detail how to write your first test and execute
that.
Before installing Appium, you need to get few other things in ecosystem:
Android SDK
Install Appium
IDE of your choice (Eclipse or IntelliJ IDea)
I am assuming that JDK installation is already there and you have the latest version of java
installed.
9
Installing Android
Installing Android
Android Requirements
Android SDK API >= 17 (Additional features require 18/19)
Appium supports Android on OS X, Linux and Windows.
http://developer.android.com/sdk/index.html
Once you download the file and unzip, you would see the below structure in the sdk folder.
Post unzipping, update the system variable to include sdk as well. For mac users below are
the command snapshot (change the path and folder name accordingly as per your machine)
export ANDROID_HOME=/Users/Steve/Development/SDK
export PATH =${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Once this is done, we need to launch the SDK manager to download relevant files to create
an emulator and run the virtual device. In terminal, type in
android sdk
This would open the SDK manager for you to download the relevant files. In the SDK
manager select the below files as shown below. This will help you create a virtual device
running Android 4.4.2.
10
Installing Android
Select the above files and choose to install, once done close the SDK manager. In terminal
then type
android avd
This would open the Android Virtual Device Manager, which would help you create the
virtual devices. Click on Create on the pop up opened and follow the below snapshot for the
values. Select the RAM size as per your machine configuration.
11
Installing Android
Once you have selected the above options, click on OK. Once done, it will show up in the
AVD manager as below.
Select the AVD name and click on Start on the right. This would launch the pop up with few
options, you may choose as you want.
"Wipe user data" would wipe any previous app installation you have done and would launch
a plain vanilla emulator.
You can use the command adb devices to see if the adb is detecting the emulator. This
basically completes the android SDK installation part.
12
Installing Android
13
Installing Appium via app
Installing Appium
Download the Appium installer from the below mentioned location. Once done extract it and
install the app.
https://github.com/appium/appium/releases
You can select the Android icon from the top and click on Launch.
Once the Appium server is running you will see some logs in the app screen or alternately
hit the below url to check the status.
http://localhost:4723/wd/hub/status
Appium can also be run via npm install. For this you would need node.js and npm version
(0.10 or greater). In order to verify if the appium is installed correctly and it's dependencies
run the command
appium-doctor
This command can be supplied with flag --android to verify all the dependencies are set up
properly.
14
Installing Appium via app
15
Installing App on Emulator
The first step is to run the emulator on which you want to install the app.
This would launch the emulator and the command would be running in the terminal.
Launch another window in the terminal and run the following steps.
16
Install Appium via npm
Brew will be very handy here to install the above stuff. It's an amazing package manager for
OS X and installing packages and updating it will be breeze once you install brew.
Once the node.js and npm are installed, you can use the below command to check if all the
appium dependencies are met, run the below command:
appium-doctor
Once this is done, start the appium server by the following command:
appium &
17
Install Appium via npm
18
Writing First Android Test
Create a new maven project and update the pom file with below mentioned Selenium
dependency. I am assuming you are familiar with Java project creation in Eclipse or IntelliJ.
Let me include a brief step by step guide to create a project.
Click Next
Give a Maven GroupID, ArtifactID, and a Version for the project, or use the defaults.
19
Writing First Android Test
Click Next
Enter Project name AppiumDemo" and Project Location Your Desired Location"
Click on Finish.
Once the project is created, copy the below dependencies in the pom.xml file.
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.46.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
</dependencies>
20
Writing First Android Test
Once the project is created, created folder called apps and put the .apk file there which is
your application under test.
Under the test folder, create a folder called "java", and create two sub folders
pages
scenarios
//mandatory capabilities
capabilities.setCapability("deviceName","Android");
capabilities.setCapability("platformName","Android");
//other caps
capabilities.setCapability("app", app.getAbsolutePath());
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilit
ies);
}
21
Writing First Android Test
Once you get the driver, from there on it's more like the Selenium usage of the appium driver
and familiar method calls.
@Test
public void helloTest()
{
String app_package_name = "com.flipkart.android:id/";
By userId = By.id(app_package_name + "user_id");
By password = By.id(app_package_name + "user_password");
By showPassword = By.id(app_package_name + "show_password");
By login_Button = By.id(app_package_name + "btn_login");
driver.findElement(userId).sendKeys("[email protected]");
driver.findElement(password).sendKeys("testvagrant123");
driver.findElement(showPassword).click();
driver.findElement(login_Button).click();
}
I am sure you would have question that why we are using "app_package_name", which is
explained in the chapter "Exploring UiAutomatorViewer".
Post this set up method you can write your normal automation test (Selenium types).
Sample code would look like:
driver.findElement(userId).sendKeys([email protected]);
driver.findElement(password).sendKeys(password);
driver.findElement(showPassword).click();
driver.findElement(login_Button).click();
We have created a project in github to help you with the basic framework setup using
Appium. Below is the github link.
22
Writing First Android Test
https://github.com/testvagrant/AppiumDemo
The above project uses Flipkart android application, which is bundled along with and is
present in the "apps" folder. The code is tested on this version of Flipkart app and works well
to show the concepts.
23
Java - Gradle Project
Click Next
Give a GroupID, ArtifactID, and a Version for the project. Click Next.
24
Java - Gradle Project
Select the option of "Use auto-import" and "Create directories for empty content...".
Click Next
25
Java - Gradle Project
Lastly enter a project name and project location and click on Finish.
26
Java - Gradle Project
27
Java - Gradle Project
```testCompile 'info.cukes:cucumber-java:1.2.4',
'info.cukes:cucumber-junit:1.2.4'
28
Understanding Desired Capabilities
Desired Capabilities are present in the below library and hence it needs to be imported.
org.openqa.selenium.remote.DesiredCapabilities
Desired Capabilities is a way of telling the Appium Server which kind of session we are
interested in. So it's a hash of Key and Value to let us have more control on the server
during automation. So some of the key info which we will be using are :
Similarly, we can specify platformVersion which will be the version of OS running on the
device, could be "8.3" or "5.1".
Below is one such table which contains the various Desired Capabilities which would be set
at the server level and customized to either Android or iOS.
29
Understanding Desired Capabilities
30
Desired Capabilities for Android
This section will list all the desired capabilities associated with Android. Majority of them are
optional but you can choose to use them as it suits your needs.
Capability Description
31
Desired Capabilities for Android
32
Desired Capabilities for Android
33
Exploring UiAutomatorViewer
While designing your UI automation suite, this tool is very helpful as it exposes the Id and
other attributes of an element, which is needed for writing scripts.
Once the android sdk path is set on the machine, open the terminal and type
uiautomatorviewer
and this would launch the UI inspection tool. Below is how the tool looks like when no app is
monitored.
Clicking on the devices icon from left takes a dump of UI XML snapshot of the screen
opened in the device. So you will be presented with an intermediate screen like this:
34
Exploring UiAutomatorViewer
Once it finishes loading, this is how the tool looks like; we have highlighted the logo of
Flipkart and the respective attribute details of the logo.
The left side of the tool shows how the device looks like and the right side is divided in two
parts:
Upper half to show the UI XML snapshot and the nodes structure
Lower half shows the details of the node selected with all the attributes.
35
Exploring UiAutomatorViewer
So if you carefully look below, you would see the resource-id, which roughly translates to id
of the HTML. And then there are other details like what is the class name, package it
belongs to, whether it is enabled, whether it is selected etc.
Apart from this all the UI elements on the left can be clicked upon and the right side changes
dynamically to show the details of the element selected.
36
Exploring Appium Inspector
When you start the Appium app, you would notice the icons at the top (image below), I have
highlighted the Apppium Inspector in red.
So if you notice that the appium server is running and the log shows that it's connected to
the emulator running locally.
When you click on the circled icon (Appium Inspector), it will launch a new UI as shown
below with the application UI state captured.
37
Exploring Appium Inspector
The panel on the extreme right is clickable and you can click on the element you want to find
details about. So if you see the panel with title "Details", there are bunch of attributes listed
for the highlighted element.
If you notice the attribute "resource-id", it's made of the package name
"com.flipkart.android" and the value of id attribute.
This package name is present for all the elements and hence we can externalize it. So to
construct an element identifier for automation, we are going to use it as shown below:
38
Exploring Appium Inspector
driver.findElement(userId).sendKeys("[email protected]");
Also you can use other options like xpath, index etc. Below is the snapshot of all the options
you have for identifying the element.
39
Remote Debugging on Android via Chrome
However, when you are working on a hybrid application (developed on a platform like
Phonegap ), we can use remote debugging.
Once the basic things are in place, connect your device to machine using USB cable.
Launch Chrome and open a tab with target "chrome://inspect". This is how it would look like.
If you notice your phone, you would have got an alert saying "Allow USB Debugging".
40
Remote Debugging on Android via Chrome
Once you click OK, your device would get showed up in browser tab. Below is how it would
show up:
41
Remote Debugging on Android via Chrome
Once you click on inspect, you can see the locators as you have always done in web for
Selenium.
You can also use Screen casting option by clicking the Screencast icon in the upper right
corner of your remote debugging DevTools window.
42
Starting Appium Server
Appium has introduced a class called AppiumDriverLocalService which will help you do
this. There are two ways you can write code:
1. If you have appium installed via npm then try the below lines of code.
service = AppiumDriverLocalService.buildDefaultService();
service.start();
service.stop();
2. If you don't have appium installed via npm then try the below lines of code. For your
local machine you might want to change the path accordingly. In the below example, I
am showing if the OS is mac then use the installed Appium to start the server. If the OS
is windows use the npm installed appium. This is just for the demonstration, ideally you
should have common strategy whether it is Mac or Windows.
43
Starting Appium Server
if (osName.contains("Mac")) {
service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
.usingDriverExecutable(new File("/Applications/Appium.app/Contents/Re
sources/node/bin/node"))
.withAppiumJS(new File("/Applications/Appium.app/Contents/Resources/n
ode_modules/appium/bin/appium.js"))
.withIPAddress("127.0.0.1")
.usingPort(port)
.withLogFile(new File("target/"+deviceUnderExecution+".log")));
}
else if (osName.contains("Windows")) {
service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
.usingPort(port)
.withLogFile(new File("target/"+deviceUnderExecution+".log")));
}
else {
Assert.fail("Unspecified OS found, Appium can't run");
}
In the code above, I have the port as parameter for parallel runs on device.
44
Executing Test on Real Devices
45
Executing Test on Real Devices
Some devices do not have Developer Options and hence the way to enable Debugging
mode is to launch the Settings screen. Once done, tap About Phone" and then scroll to the
bottom and tap on "Build Number" 7 times (Yes 7 times)!
Once done, you will now be able to enable/disable it whenever you desire by going to
Once the above set ups are done, launch Terminal (or Command Prompt) and type in
adb devices
There are times when even after starting USB mode on your device, adb wouldnt list the
device here. To fix that, below are some of the steps you need to follow:
46
Executing Test on Real Devices
Once you have copied the vendor ID, we need to update the file below using the following
command:
vim ~/.android/adb_usb.ini
This is how a sample file would look like after updating the Vendor ID.
47
Executing Test on Real Devices
Once the above changes are done, run the following commands:
adb kill-server
adb start-server
adb devices
This would finally show up the devices as connected. Once the device shows up as online,
we are good to run the test.
In case you have any android version mentioned in your code, you can remove it and have
only the one, which are mandatory. Below is a sample snippet I have used and works
flawlessly.
//other caps
capabilities.setCapability(app, app.getAbsolutePath());
driver = new RemoteWebDriver(new URL(http://127.0.0.1:4723/wd/hub), capabilities);
48
Working with Genymotion Emulator
Introduction
A Genymotion emulator is a virtual device which runs on your system and like a typical
android emulator. It's an emulator based on Virtualbox. It can emulate a bunch of android
devices and support a wide variety of API levels. Since the Virtualbox is cross platform
compatible, it allows Genymotion to be used on any platform be it windows, Linux, Mac.
Genymotion allows you to create custom device image as well as standard device image
which is easy to download and get started. Its an emulator using x86 architecture
virtualization, making it much more efficient.
Genymotion has a free version and license one as well. Even in free version you will see a
wide range of devices supported and the android version. Download and install the
Genymotion app. Once done you should be able to log in with your registered credentials
and launch the Genymotion app. This will open up a window shown below and give you
option to choose device or android version.
49
Working with Genymotion Emulator
50
Working with Genymotion Emulator
Once you download the required device image, if the app depends on Google Play, you
need to do 2 things:
51
Automating Gestures
single tap
double tap
flick (left or right)
pull down to refresh
long press
Appium handles these gestures using TouchActions api they have created. Its more like
Actions class in Selenium. Apart from that they have also enabled JSON wire protocol
server extensions.
We can pass in coordinates as parameters and specify the action we want. Sample code
would look like as:
When we enter the coordinates in decimal, it actually specifies the percentage. So in above
example it means, 1% from x and 50% from y coordinates. Duration basically specifies how
long it will tap and is in seconds.
mobile: tap
mobile: flick
mobile: swipe
mobile: scroll
mobile: shake
52
Automating Gestures
You might also want to explore TouchActions class provided by Selenium. It implements
actions for touch devices and basically built upon the Actions class.
We have added some test in the git project to show how to use the gestures in automation.
The project would help you learn how to automate android app using Appium.
Appium let's you do a scroll to the element text but sometimes it might not work depending
on how app is and CSS structure are. You can write your own parallel code to perform scroll
and here is the code snippet for the same.
53
Tips (With Code Snippets)
Most of the time when you are testing an app, you will find that there is a specific page in
app which is a Webview and your normal code is not working. So in those situations we
need to change the application context to "WEBVIEW" or "NATIVE" accordingly. Below is a
code snippet will do the same and change the context to Webview.
A similar code can be used with Native as parameter to change the context to Native app.
Generally when you write an automation script you should try to write a code which runs in
an un-attended mode. Starting Appium Server and killing it when the test is run is one thing
which we should be handling with in the framework. Below code snippet will help you do the
same. So if you notice the below code, we are using the installed appium to start the server
and then the "port" on which we start is parameterized. Also we are generating an appium
log file so as to capture the appium log which is again parameterized based on the device
under execution.
54
Tips (With Code Snippets)
55
Running multiple Appium Server for parallel execution
So how do you run the test in parallel ? One of the approach I would suggest here is to have
multiple appium server running. Steps to do it:
Run the below command and replace the udid with actual device udid and port with
values from (4723)
appium -U udid -p port
For second device update the udid and increment the port value by 10
Appium gives a way to do the same via code by giving AppiumServiceBuilder class. Below is
a sample code which takes input param as port and udid. In Appium 1.5.3 release they have
move the udid to GeneralServerFlag as Robot_Address.
def service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
.usingDriverExecutable(new
File("/Applications/Appium.app/Contents/Resources/node/bin/node")) .withAppiumJS(new
File("/Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js"))
.withIPAddress("127.0.0.1") .usingPort(port as int)
.withArgument(GeneralServerFlag.ROBOT_ADDRESS, udid as String)
.withArgument(AndroidServerFlag.BOOTSTRAP_PORT_NUMBER, ((port as int) + 2) as String)
.withArgument(SESSION_OVERRIDE) .withLogFile(new File("build/${device}.log")));
So the above command helps you create the appium service which then you can start as
service.start
The next work would be to create a mapping of tag and the devices on which you want to
run the test. This could be done via a properties file.
56
References
References
Official Site & Tutorials
http://appium.io/
https://docs.saucelabs.com/tutorials/appium/
Android SDK
https://developer.android.com/sdk/index.html?hl=i
Github Project Link
https://github.com/appium/appium
https://github.com/testvagrant/AppiumDemo
Resources
http://testvagrant.com/#!blogs/c152q
Appium Discussion Group
https://discuss.appium.io/
Selenium
https://code.google.com/p/selenium/wiki/JsonWireProtocol
http://www.seleniumhq.org/
UI Automation Documentation
https://developer.apple.com/library/ios/documentation/DeveloperTools/Reference/UI
AutomationRef/_index.html
UI Testing Android *http://developer.android.com/tools/testing/testing_ui.html
57