Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the application practice of Appium in Android UI testing

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What is the application practice of Appium in Android UI testing? I believe many inexperienced people are at a loss about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Brief introduction of Android testing tools and Appium

Appium is a testing framework that supports Android/iOS Native, Hybrid and Mobile Web Apps, and communicates with test programs through the Selenum Webdriver protocol. The advantage of Webdriver is that the procedure on Server is called by HTTP RPC, and the writing of test script is not limited by language. No matter it is Python, Java or NodeJS, it is convenient to write tests. Python will be used for programming in this article.

The cause is due to the following demand from colleagues in the marketing department: add some Wechat friends in batches. The method of directly grabbing the request for replay is unreliable. The communication between Wechat and the server is encrypted, Pass. Consider using framework hook related functions such as xposed to operate. But xposed needs jailbreak, and the development is complex, Pass. Later, I thought of using the UI testing tool for simulation operation, and the development is relatively simple.

There are many Android UI testing tools, such as Monkey, UIAutomator, Selendroid, Robotium and so on. Among them, UIAutomator, Monkey and Selendroid are all non-invasive UI tests, that is, they do not need to modify the source code, but can be tested as long as the target program is installed. Robotium needs to be compiled and tested with the source code. Appium is actually a unified scheduling software for testing tools, which integrates different non-intrusive testing tools to provide a unified API. In versions prior to Android 2.3, Appium would call Selendroid, and later versions would use UIAutomation directly under UIAutomator,iOS. Appium also supports UI testing for FirefoxOS.

Install Appium

The official website gives the installation method under the command line. But in fact, Appium has a GUI version, which is more suitable for use under Windows/MacOS. .net Framework needs to be installed under Windows.

> brew install node # get node.js > npm install-g appium # get appium > npm install wd # get appium client > appium & # start appium > node your-appium-test.js

Appium needs to rely on Android SDK to compile two plug-ins that run on the mobile side, so you need to install the corresponding Android SDK version first. The SDK Manager that comes with Android Studio is used directly here. Select the SDK Platform and newer Build-tools corresponding to the test machine in the SDK Manager, and install the corresponding ARM/x86 System Image and Intel HAXM Installer to accelerate the x86 virtual machine if you need to use the simulator to test. Appium uses adb to communicate with the target machine, so the operation for the real machine and the simulator is almost the same, and how to build the simulator will not be discussed here.

After the installation is complete, you need to configure the Android SDK directory in Appium GUI, then select Android and click Launch to start Appium Server.

Appium Server listens to http://localhost:4723 by default for RPC communication. Now we can open up the familiar programming environment and write UI test cases. Using Python to write here, you need to install Python Client of Appium first, and then use appium.webclient in python to connect to Appium server.

Pip install Appium-Python-Client

Using Appium for UI control

After you modify the appropriate properties according to the comments, you can run the test. The phone needs to open ADB for debugging. After executing the following code, Appium will install Appium Settings and Unlock programs on the phone, and then Wechat will be started.

From appium import webdriver desired_caps = {} desired_caps ['platformName'] =' Android' # Test platform desired_caps ['platformVersion'] =' 5.1'# platform version desired_caps ['deviceName'] =' m3roomnote' # device name For multiple devices, you need to distinguish between desired_caps ['appPackage'] =' com.tencent.mm' # app package name desired_caps ['appActivity'] =' .ui.LauncherUI'# app default Activity dr = webdriver.Remote ('http://localhost:4723/wd/hub', desired_caps) # launch Remote RPC

Selenum Webdriver uses a method similar to the DOM model in JS to select elements in the page. Dr is the currently active activity object, and you can use the method of findElementByXXX to get the elements in Activity. All functions with s after Element get all matching elements, and functions without s get * matching elements.

Query function

1. FindElement (s) ByName

It is basically useless in Android. Android UI does not have the attribute Name. It is said that it can be obtained by using the text value. But I didn't succeed.

2. FindElement (s) ByClassName

Get the element by the class name, as follows:

Item_list = dr.find_elements_by_class_name ("android.widget.LinearLayout") item_list [2] .click ()

3. FindElementById

Get the element through resource_id, which is * * in each Activity, and the usage is as follows

T = dr.find_element_by_id ("com.tencent.mm:id/f7") t.send_keys (wechatId)

4. FindElement (s) ByAccessbiltiyId

On Android, AccessbilityID is actually contentDescription. This property is set to facilitate the use of mobile phones by visually impaired people. When TTS is enabled, the system will read the contentDescription of the relevant controls.

5. FindElement (s) ByXPath

Find the element through the XML Path description. I didn't get it successfully, maybe there's something wrong with XPath's writing.

S = dr.find_element_by_xpath ("/ / android.widget.TextView [contains (@ text,' search')]") s.click ()

6. FindElementByAndroidUIAutomator

Get the element through the selector of UIAutomator. Because Appium is actually a calling UIAutomator on Android, you can select elements through UIAutomator's selector.

El = dr.find_element_by_android_ui_automator ("new UiSelector () .text (\" search\ ") el.click ()

Operation function

Operation functions are used to manipulate the selected elements, there are many, just a few below, please refer to the manual for more.

Click

Send_keys

Clear

The element object returned by the query function can continue to use the query function to select its child elements, just like the dom element in JS. The use cases are as follows.

Search = dr.find_element_by_id ("com.tencent.mm:id/aqw") .find_element_by_class_name ("android.widget.RelativeLayout") search.click ()

How to determine query rules

Now that you know the relevant functions, it's time to locate UI. If it is a program developed by your own team, it is recommended that you add resource_id to all spaces for absolute positioning. If you encounter an element that does not negotiate a price resource_id, you will have to use another way to locate it.

1. UI Automator Viewer

UI Automator Viewer is the official UI positioning tool of Android, which is located under sdk/tools. The viewer interface opens after running. Click the get button to get the UI structure of the currently running Activity.

2. AppiumDriver getPageSource

AppiumDriver (Client) can easily get the UI description of the currently running Activity, and then look for elements based on the returned XML document.

Print dr.page_source

Once the location of the element is determined, the element can be found / selected according to the aforementioned Find method

Write complete test code

After getting the element correctly, you can get the information about the element, and then write the test using the test framework commonly used in various languages, such as Java's JUnit,Nodejs 's Mocha and so on.

Here I use Appium mainly to simulate users clicking to add Wechat friends, so the complete program does not use the test framework. The relevant UI element acquisition / operation methods for your reference.

# coding:utf-8 from appium import webdriver from time import sleep def addFriend (dr, id, dryRun=False): succ = False wechatId = str (id) dr.find_element_by_accessibility_id (r "more function button"). Click () item_list = dr.find_elements_by_class_name ("android.widget.LinearLayout") try: item_list [2] .click () except: print "Error! In item list len "return succ el = dr.find_element_by_class_name (" android.widget.ListView ") item_list = el.find_elements_by_class_name (" android.widget.LinearLayout ") try: item_list [1] .click () except: print" Error! In item list len "return succ t = dr.find_element_by_id (" com.tencent.mm:id/f7 ") t.send_keys (wechatId) search = dr.find_element_by_id (" com.tencent.mm:id/aqw "). Find_element_by_class_name (" android.widget.RelativeLayout ") search.click () try: freq = dr.find_element_by_id (' Com.tencent.mm:id/aqq') assert freq.text = = u "operate too frequently Please try again later. " Print "Frequency too high! Sleep 300s "sleep (60) return succ except: pass try: dr.find_element_by_id ('com.tencent.mm:id/a8x'). Click () addBtn = dr.find_element_by_id (' com.tencent.mm:id/eu') if not dryRun: addBtn.click () succ = True Print "Success Send Requests:" + wechatId except: print "No Such User Or Already a Friend:" + wechatId while True: try: dr.find_element_by_id ('com.tencent.mm:id/fb'). Click () except: try: dr.find_element_by_id (' com.tencent.mm:id/f4'). Click ( ) except: break return True def resetActivity (dr Desired_caps): dr.start_activity (desired_caps ['appPackage'], desired_caps [' appActivity']) desired_caps = {} desired_caps ['platformName'] =' Android' desired_caps ['platformVersion'] =' 5.1 'desired_caps [' deviceName'] = 'm3notebook' desired_caps ['appPackage'] =' com.tencent.mm' desired_caps ['appActivity'] =' .ui.LauncherUI 'print "Trying connect to phone..." Dr = {} try: dr = webdriver.Remote ('http://localhost:4723/wd/hub', desired_caps) except Exception, e: print "Cannot Connect to phone:", e exit () print "Successfully connect to phone." Print "Reading friend list..." FriendList = [] fp = open ("friends.txt") line = fp.readline () .strip () while line: friendList.append (line) line = fp.readline () .strip () print "Finish reading friends. Total:" + str (len (friendList)) print "Wait for Wechat's splash screen...." For i in range (0,10): print 10-I sleep (1) succ_list = [] fail_list = [] for i in friendList: try: succ = addFriend (dr, I, dryRun=False) if succ: succ_list.append (I) else: fail_list.append (I) except: fail_list.append (I) resetActivity (dr Desired_caps) print "Succeed List:" print "\ n" .join (succ_list) print "Failed List:" print "\ n" .join (fail_list) dr.close () finish reading the above Have you mastered the application practice of Appium in Android UI testing? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report