This Appium tutorial will show you how to run automated tests on a real physical device. We estimate skimming through this post will take you 10 minutes. We estimate working through this post, step by step, will take you about 90 minutes. In this post we will cover getting setup with Appium, interfacing with real devices, writing and running Appium tests. We also briefly introduce you to multiple ways to locate UI elements.
NOTE: If you have an Android phone handy, you can follow along easily. If not, you may be interested in a previous post showing you how to get started with Appium on an emulator.
Why this post?
There are two compelling reasons for this post.
1. Mobile devices are taking over the world
In recent times there is a lot of interest in mobile testing. And rightly so. The mobile space is growing. The apps are the new cool thing. The mobile space is ideal for software testers looking to learn new things and keep current.
2. Lack of high quality tutorials on mobile automation
One big challenge in the mobile automation space is the the limited amount of information about the technologies. Quality sources of information on mobile automation is very limited.
So here is a high quality and informative tutorial for the hands-on tester who wants to get started with Appium and mobile automation on a physical mobile device.
Why Appium?
There are quite a few number of tools out there in the mobile automation market like MonkeyTalk, Calabash, Robotium, etc. Each has its own advantages and limitations. Some of these tools require an agent to be installed, the application has to be recompiled so that the tool can interact with the mobile app, etc. However Appium is built on the idea that testing native apps shouldn’t require including an SDK or recompiling the app. Appium is also an open source project – so if you are not happy with it, you can contribute and enhance it. Appium tests run against both on iOS and Android. For me, Appium (while still being extremely immature), looks to be the standout technology that will own the mobile UI automation space. Appium reminds me of the early Selenium versions I used. Based on history, I think Appium will be the front-runner in the mobile UI automation space.
Step by step Appium tutorial
We have already shown you how to run an Appium test using an emulator in one of our previous posts. In this post, I will show you how to test an app using a real device. Being a tennis fan, I decided to test a tennis app. On my Android phone, I downloaded the ATP/WTA app and decided to automate some of the functionality of this app. I will also show you how to navigate through different pages in the app using different locator strategies, get data from a table using Appium and Python and how to use the uiautomator to find UI components of the page.
Overview
1. Appium setup
2. Connect to an Android device
3. Select an app to test, get its package and activity name
4. Use uiautomatorviewer to find UI components of the application
5. Write the test
6. Start and launch Appium server console
7. Run the test
8. View the test result
STEP 1: Appium setup
Download and install Android SDK and Appium along with Appium’s client libraries for Python. Installations are fairly straight forward. However if you need help, please refer to the setup section in our previous blog for a more detailed process on how to set up Appium on your machine.
STEP 2: Connect to an Android device
You have to enable USB debugging in your phone to be able to run your test scripts. For this, first, you need to enable “Developer options” by navigating to Settings/About Phone and tapping build number seven times. You will get a notification saying that you’re now a developer. Ignore it – you are still a tester ;). Once you are a developer you need to navigate to “Developer options” and enable the USB debugging option. You can refer to this link for more details
Note: On some devices, you may have to download some device drivers to connect your phone to the PC
STEP 3: Select an app to test, get its package and activity name
You can go to Google Play Store and download the ATP/WTA app. We will automate some of the functionality like navigating to the ATP Singles Rankings view to assert that Novak Djokovic is the first player listed and also get his personal details from the table in players view.
In order to start the app we would need the app Package and Activity name. We can get these details from the apk file of the app. Instead of downloading the apk file and looking into app manifest file for this detail, we can also download some really cool apps which can get you these details. Apk Info is one such app which you can download from Play Store and get the app Package and Activity details. Just download the app and click on Apk Info Icon which will list all the apps on your device. Click on your app to get the details required as shown below
STEP 4: Use uiautomatorviewer to find UI components of the application uiautomatorviewer is a GUI tool to scan and analyze the UI components of an Android application. To click or to navigate to any components in your app you need to identify the UI components of your application. Using uiautomatorviewer you can take the snapshot of the UI screen on any Android device that is connected to your machine. You can then inspect the layout hierarchy and view the properties of the individual UI components that are displayed on the device.
Connect your Android device to your machine and open the app you are testing. In your machine open a terminal window and navigate to the path $android-sdk /tools and run the command to open Uiautomatorviewer
$ uiautomatorviewer |
To capture a screen, click the “Device Screenshot button” in the uiautomatorviewer tool. The screenshot of the page in your device is captured. You can move over the snapshot in the left-hand panel to see the UI components identified by the uiautomatorviewer. You can view the component’s properties listed in the lower right-hand panel, and the layout hierarchy in the upper right-hand panel.
STEP 5: Write the test
We will launch the ATP WTA app using the package and activity name we found out and then navigate through various pages using different locator strategies. While we do not recommend using multiple locator strategies, we are doing so in this tutorial only to make you aware of your options. Then we will confirm that Novak Djokovic is the top player listed in ATP Singles Rankings list view and get his personal details from a table in Players view.
""" Qxf2: Example script to run one test against ATP_WTA app using Appium The test will navigate to ATP Singles Rankings list and confirm that Novak Djokovic is the top player listed and get his personal details from a table. """ import unittest, time, os from appium import webdriver from time import sleep class Android_ATP_WTA(unittest.TestCase): "Class to run tests against the ATP WTA app" def setUp(self): "Setup for the test" desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['platformVersion'] = '4.4' desired_caps['deviceName'] = '$ Your device name' # Since the app is already installed launching it using package and activity name desired_caps['appPackage'] = 'atpwta.live' desired_caps['appActivity'] = '.activity.Main' # Adding appWait Activity since the activity name changes as the focus shifts to the ATP WTA app's first page desired_caps['appWaitActivity'] = '.activity.root.TournamentList' self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) def tearDown(self): "Tear down the test" self.driver.quit() def test_atp_wta(self): "Testing the ATP WTA app " self.driver.implicitly_wait(30) time.sleep(5) # click on Navigation Bar MainMenu by finding element by xpath menubar = self.driver.find_element_by_xpath("//android.widget.Spinner[@resource-id='atpwta.live:id/NavBarMainMenuSpinner']") menubar.click() # From list of options available click on Rankings by finding element using uiautomator rankings = self.driver.find_element_by_android_uiautomator('new UiSelector().text("Rankings")') rankings.click() # click on ATP Singles by finding element using id singles = self.driver.find_element_by_id('atpwta.live:id/RankingsListItem') singles.click() # Assert that Novak Djokovic is the top listed player elmnt = self.driver.find_element_by_id('atpwta.live:id/Player1TV') self.assertEqual('Novak Djokovic', elmnt.get_attribute('text')) print elmnt.get_attribute('text') elmnt = self.driver.find_element_by_xpath("//android.widget.LinearLayout[@index=0]") elmnt.click() # Print the contents of Table listed for the top ranked player table = self.driver.find_element_by_android_uiautomator("new UiSelector().className(android.widget.TableLayout)") rows = table.find_elements_by_class_name('android.widget.TableRow') for i in range(0, len(rows)): cols = rows[i].find_elements_by_class_name('android.widget.TextView') for j in range(0, len(cols)): print(cols[j].get_attribute('text')+" -- "), print("") #---START OF SCRIPT if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(Android_ATP_WTA) unittest.TextTestRunner(verbosity=2).run(suite) |
STEP 6: Start and launch Appium server
Start Appium server console by double-clicking on the Appium file. Click on the ‘rocket’ icon to launch the Appium node server.
Please refer to the 6th and 7th step of our previous blog if you need more details on starting appium server.
STEP 7: Run the test
You can run the test any way you like. We will run it using the command prompt. The app gets launched in your device and navigates to a different screen.
Game. Set. Match. You learnt how to do mobile automation using Appium on a real device! If you are still hungry for more, take a tour of our open-sourced web and mobile automation framework.
I am a dedicated quality assurance professional with a true passion for ensuring product quality and driving efficient testing processes. Throughout my career, I have gained extensive expertise in various testing domains, showcasing my versatility in testing diverse applications such as CRM, Web, Mobile, Database, and Machine Learning-based applications. What sets me apart is my ability to develop robust test scripts, ensure comprehensive test coverage, and efficiently report defects. With experience in managing teams and leading testing-related activities, I foster collaboration and drive efficiency within projects. Proficient in tools like Selenium, Appium, Mechanize, Requests, Postman, Runscope, Gatling, Locust, Jenkins, CircleCI, Docker, and Grafana, I stay up-to-date with the latest advancements in the field to deliver exceptional software products. Outside of work, I find joy and inspiration in sports, maintaining a balanced lifestyle.
Hi,
This is excellent. I can run this successfully. Thanks for this. I was waiting for this. Great job. Keep it up.
How to capture the screen for each steps?
Thanks
Selva
Thanks, Selva! We are always happy to help out fellow testers.
When you say “capture the screen” do you mean taking a screenshot as part of the script itself? Or did you mean how we captured the screenshots pasted in this tutorial?
Hi ,
Thanks for getting back to me. I mean talking screenshot as part of the script itself.
Once again thanks.
Selva, I have not tried this and won’t be able to try this for the next few days. But I think self.driver.get_screenshot_as_file(filename) should do it. I know Appium’s webdriver inherits from Selenium’s webdriver.Remote. Selenium’s webdriver.Remote has the method get_screenshot_as_file(filename) where filename is the full path of the desired image. E.g.:self.driver.get_screenshot_as_file(r’C:\tmp\my_image.png’)
Side note: A useful Python feature is to use the help(object) command in the Python interpreter. You can create the driver object and then do help(driver) to see what are the methods that can be used with that object.
Selva, I can confirm that self.driver.get_screenshot_as_file(r’C:\tmp\my_image.png’) works for me.
Hi,
Thanks for your help.
Hi
I followed your tutorial as follows:
1. Appium setup – Yes
2. Connect to an Android device – Yes (Nexus 4 running Android 4.4.2, with Dev mode enabled)
3. Select an app to test, get its package and activity name – Downloaded ATP/WTA Live app and installed on Nexus 4.
4. Use uiautomatorviewer to find UI components of the application – Skipped
5. Write the test – Copied the test from this page and saved as atp_wta.py, and modified platformVersion and deviceName.
6. Start and launch Appium server console – Yes
7. Run the test – Yes
But I’m getting the following error:
C:\Dev\appium_python_tests>python atp_wta.py
test_atp_wta (__main__.Android_ATP_WTA)
Testing the ATP WTA app … ERROR
======================================================================
ERROR: test_atp_wta (__main__.Android_ATP_WTA)
Testing the ATP WTA app
———————————————————————-
Traceback (most recent call last):
File “atp_wta.py”, line 18, in setUp
self.driver = webdriver.Remote(‘http://localhost:4723/wd/hub’, desired_caps)
File “C:\Dev\Python27\lib\site-packages\appium_python_client-0.11-py2.7.egg\appium\webdriver\webdriver.py”, line 35, in __init__
super(WebDriver, self).__init__(command_executor, desired_capabilities, browser_profile, proxy, keep_alive)
File “C:\Dev\Python27\lib\site-packages\selenium-2.44.0-py2.7.egg\selenium\webdriver\remote\webdriver.py”, line 73, in __init__
self.start_session(desired_capabilities, browser_profile)
File “C:\Dev\Python27\lib\site-packages\selenium-2.44.0-py2.7.egg\selenium\webdriver\remote\webdriver.py”, line 121, in start_sess
ion
‘desiredCapabilities’: desired_capabilities,
File “C:\Dev\Python27\lib\site-packages\selenium-2.44.0-py2.7.egg\selenium\webdriver\remote\webdriver.py”, line 173, in execute
self.error_handler.check_response(response)
File “C:\Dev\Python27\lib\site-packages\selenium-2.44.0-py2.7.egg\selenium\webdriver\remote\errorhandler.py”, line 166, in check_r
esponse
raise exception_class(message, screen, stacktrace)
WebDriverException: Message: A new session could not be created. (Original error: Could not find a connected Android device.)
———————————————————————-
Ran 1 test in 28.133s
FAILED (errors=1)
What am I doing wrong? Any help would be greatly appreciated.
Thanks
Leo
Leonardo, the error indicates that your Android device may not have been recognized. I’ll need more details to debug. What do you see when you run adb devices -l on your command prompt? You may need to change the directory to you_android_path\sdk\platform-tools for the adb command to work.
Please let us know the version of Android you have on your phone too.
Hi, yes, my laptop didn’t recognise my device but I have sorted it out since, by following the steps outlined here: http://bit.ly/1y93bXt, and now I get this message when I do adb devices:
List of devices attached
025f18afd8d66506 device
So, now when I run the python script, I get this new error:
test_atp_wta (__main__.Android_ATP_WTA)
Testing the ATP WTA app … ERROR
======================================================================
ERROR: test_atp_wta (__main__.Android_ATP_WTA)
Testing the ATP WTA app
———————————————————————-
Traceback (most recent call last):
File “atp_wta.py”, line 18, in setUp
self.driver = webdriver.Remote(‘http://localhost:4723/wd/hub’, desired_caps)
File “C:\Dev\Python27\lib\site-packages\appium_python_client-0.11-py2.7.egg\appium\webdriver\webdriver.py”, line 35, in __init__
super(WebDriver, self).__init__(command_executor, desired_capabilities, browser_profile, proxy, keep_alive)
File “C:\Dev\Python27\lib\site-packages\selenium-2.44.0-py2.7.egg\selenium\webdriver\remote\webdriver.py”, line 73, in __init__
self.start_session(desired_capabilities, browser_profile)
File “C:\Dev\Python27\lib\site-packages\selenium-2.44.0-py2.7.egg\selenium\webdriver\remote\webdriver.py”, line 121, in start_sess
ion
‘desiredCapabilities’: desired_capabilities,
File “C:\Dev\Python27\lib\site-packages\selenium-2.44.0-py2.7.egg\selenium\webdriver\remote\webdriver.py”, line 173, in execute
self.error_handler.check_response(response)
File “C:\Dev\Python27\lib\site-packages\selenium-2.44.0-py2.7.egg\selenium\webdriver\remote\errorhandler.py”, line 166, in check_r
esponse
raise exception_class(message, screen, stacktrace)
WebDriverException: Message: A new session could not be created. (Original error: Requested a new session but one was in progress)
———————————————————————-
Ran 1 test in 0.303s
FAILED (errors=1)
Leonardo, can you try restarting your Appium server? I have seen this happen when driver.quit() is not called at the end of one script and you try to run a new one. E.g.: You ran a script and somewhere the script failed with an exception before driver.quit() was called. Now you correct the error in the script and run it again and sometimes this error happens. Annoying. Only quick fix I can think of is to restart the Appium server.
Thank you. That did the trick! It would also help others if you add a small section of FAQ at the end of this article if case others have come across these types of errors with Appium.
Now I can follow the rest of your tutorials and even try writing my own tests! Thanks again.
Great, test away! I like your idea about an FAQ section, Leonardo. Thanks! Based on the comments here, I will add the FAQ to this post. I should get to doing it in the next couple of weeks.
Hi,
Great article .
Can you please elaborate in general the concept of how can I do image recognition to identify and control GUI components.
Thanks In Advanced,
Eldad, I have used image comparison in the non-mobile space. In various projects, I have used EggPlant, AutoIT and Screenster. I have also written my own Python scripts using a combination of ImageMagick and Python Image Library. How you end up doing image recognition depends on your specific use case. Sometimes its just a matter of scaling the image to a known size, comparing it with a reference and then working out the co-ordinates that you want to click. Other times, it may be a matter of super-imposing two images and taking a pixel by pixel difference (with an error margin) to determine an exact match.
Having said all that, I would strongly discourage you from using image comparisons unless that is literally your last unexplored alternative. To date, I have not found a single tool that is based on image recognition that is even moderately robust enough for professional use.
Thanks on a detailed & professional answer.
Are there any tools that wraps Appium for more less-code tool for QA engineers that are not writing code?
Thanks
Eldad, I am not familiar with the record & play space. I know a tool called “Appium GUI” exists and is supposed to work ok with iOS. But I have not used it with either Android or iOS.
Hi,
Can you please how to do i do for Pich and swipe on screen on android using appium api.
thanks
Selva
Hi Selva,
We would be writing a blogpost on Pinch and swipe gestures on android using appium, within next week
Thanks. let me know when you done that.
Hi Selva,
The blog may take bit time, so here is some sample code for swipe, pinch and zoom which may be helpful for you.
For swipe use:
driver.swipe(startx, starty, endx, endy, duration)
eg: self.driver.swipe(475, 500, 75, 500, 400)
For pinch and zoom:
self.driver.pinch(element = el)
self.driver.zoom(element = el)
I tested this with camera app and below is the code snippet
el = self.driver.find_element_by_class_name(‘android.view.View’)
self.driver.pinch(element = el)
time.sleep(5)
self.driver.zoom(element = el)
time.sleep(5)
action.long_press(el).perform()
Note: pinch and zoom doesn’t work for android 4.2 or lower versions
Hi,
Thanks for your continues help. You are doing very excellent jobs. Well done and keep it up.
Regards
Selva
Hi,
Thanks for your help. You are doing excellent jobs. Well done keep it up.I have learned so much from you. it is good idea to consider doing on line tutorial or you tube video as you have very good talent.
Regards
Selva
Hi,
Thanks for your help. You are doing excellent work. I advice you to do some online tutorial or You tube series of Video.
Thanks
Selva