关于UIautomator API及浅析

从android sdk api 16开始,Android SDK开始支持两个做功能UI测试的新工具。
uiautomatorviewer,一个用以扫描以及分析Android应用程序的UI部件的工具。
以及uiautomator ,一个提供API用以自定义UI测试的Java库。
要应用上面两个工具,除了需要android sdk api 16以上的前提条件外,还要求Android SDK Tools为21版以上。

UiAutomator主要涉及一下几个类,大多数位于源码包的com.android.uiautomator.core下,其中粗体字部分为主要会接触到的类,熟知这5个类的作用,就可以大体顺畅的写出UiAutomator的测试用例。

UiAutomatorTestCase
UiDevice
UiSelector
UiScrollable
UiObject
UiCollection

UiTestAutomationBridge, UiAutomatorBridge
InteractionController, QueryController
UiWatcher

UiAutomatorTestCase

TestCase (Junit) -> UiAutomatorTestCase  -> App Test

每个测试用例都需要继承UiAutomatorTestCase,以实现测试环境的setup,teardown等同能。而UiAutomatorTestCase则是通过继承Junit3中的TestCase类,并在其中的setUp() 、tearDown() 、getParams() 函数中。其中主要是用Bundle实现Android Activity之间的通讯。在UiAutomatorTestCase,还加入了getUiDevice()等关于UiDevice的 函数,以实现在测试的任意地方均可调用UiDevice()。

UiDevice

此类主要包含了获取设备状态信息,和模拟用户至于设备的操作两类api。

可以通过getDisplaySizeDp(), getDisplayWidth() , getDisplayHeight() ,getProductName() ,getCurrentActivityName(), getCurrentPackageName() 等获取设备相关信息。

pressMenu(), pressBack(), pressHome(), pressSearch() ,pressDPadCenter(), pressDPadRight(), pressDPadLeft(), pressDPadUp(), pressDPadDown() ,pressDelete(), pressEnter(), pressKeyCode(), pressRecentApps(),click(),swipe(),getDisplayRotation() setOrientationLeft()… wakeUp(), sleep() ,dumpWindowHierarchy(), waitForWindowUpdate()等API可以灵活的操纵设备。

而takeScreenshot() 允许随时对设备截屏。

UiSelector

主要是通过一定查询方式,定位到所要操作的UI元素。

一般UI元素均可通过以下API定位:text(), textMatches(String regex), textStartsWith(), textContains() ,className() ,classNameMatches(String regex), className(Class type) ,Description(), descriptionMatches(String regex),descriptionStartsWith(),descriptionContains() ,packageName(), packageNameMatches(String regex)。

值得注意的是index()和 instance() 两个函数,其中index()是当前页面的ID编号,instance()则表示在一定都搜索结果下,获取的子元素集的第几个元素。如:
new UiSelector().className("android.widget.ImageView").enabled(true).instance(2);

另有enabled(), focused(), focusable(), scrollable(), selected(), checked(), clickable() ,longClickable() ,childSelector()等检索条件,顾名思义。

UiObject

UiObject可代表页面的任意元素,它的各种属性定位通常通过UiSelector来完成。

比较常用的Api如clickAndWaitForNewWindow(),表示点击该元素,并且等待新新窗口的展示完毕。这一过程是Android UI Testing框架支持的,不需要额外的控制等待时间。

UiObject允许点击该元素的具体一个部分,Api如clickTopLeft(), longClickBottomRight(),… 

通过getText(), getContentDescription(), getVisibleBounds(),… 等api可获取UiObject的相关属性,getPackageName() 可用来明确是否打开了目标测试的App.

setText(), clearTextField() 可以 用来设置以及清空所关联的输入框。

waitForExists() 可以用来操纵相关等待或验证。

UiCollection

UiCollection一般与UiSelector连用,如它的构造函数也要求提供Uiselector: UiCollection(UiSelector selector)。
它的api较少,主要用以从Uiselector筛选出的元素集中挑出所要的元素:getChildByDescription(), getChildByInstance(), getChildByText() ,以及统计元素集的个数getChildCount()


UiScrollable

UiObject -> UiCollection ->UiScrollable

UiScrollable 用来表示可以滑动的界面元素,其继承关系如上图所示。

其Api中,setAsVerticalList(), setAsHorizontalList() 用以设置Ui元素列表是基于横向滚动还是纵向滚动。其后可以用getMaxSearchSwipes() ,flingForward(), flingBackward() ,scrollForward(),scrollBackward() ,scrollToEnd(), scrollToBeginning() 等函数控制滑动,以及getChildByDescription(), getChildByInstance(), getChildByText() ,scrollIntoView(), scrollTextIntoView(),… 来选择是否已经转换到具有目标元素的页面。如:
UiScrollable appViews = new UiScrollable(new UiSelector().scrollable(true));
appViews.setAsHorizontalList();
UiObject helperApp;
helperApp = appViews.getChildByText(new UiSelector()
.className(android.widget.TextView.class.getName()), " 91助手 ");  则若当前页面没有91助手APP, 测试会自动滑动页面,直到91助手App出现。

下面介绍下UI Testing Framework构成的重要类:

UiTestAutomationBridge

这是整个Testing Framework的基础,此类负责连接系统了,记录最新的可链接事件(AccessibilityEvent) , 窗口内容查询Api等。可以被Android App调用,或者Java程序从shell调用。

这里需要注意两个概念:

1、AccessibilityEvent:所有的Ui元素可以被操纵,因为这些Event都是AccessibilityEvent。对于怎样令页面元素可以被操纵,使得相关的事件都是AccessibilityEvent,请参见Uiautomator 词条-"确认程序可以被测试" 部分。
2、AccessibilityNodeInfo:视窗中的组件树节点,也就是uiautomtorViewer中展示的各个节点。
Api中connect(), disconnect() 负责建立与设备的实际连接。
executeCommandAndWaitForAccessibilityEvent() performAccessibilityAction() findAccessibilityNodeInfosByText(), findAccessibilityNodeInfoByViewIdInActiveWindow() 都是其中重要的Api。

UiAutomatorBridge

UiAutomatorBridge是UiTestAutomationBridge的子类,区别主要是在构造函数中加上了InteractionController 和QueryController 两大对象的调用。以及一些常量定义等。除了上述差异,UiAutomatorBridge还定义了executeCommandAndWaitForAccessibilityEvent() 、onAccessibilityEvent() 、waitForIdle() 、addAccessibilityEventListener() 等函数。

InteractionController

介绍InteractionController,需要先提InteractionProvider,它负责注入用户事件(如点击、输入等) ,并且反应事件的对应坐标。
InteractionController则定义了几乎所有至于手机的基础操作,如runAndWaitForEvents(), clickAndWaitForEvents() ,click(), longTap(), scrollSwipe(),Swipe() ,clickAndWaitForNewWindow() ,touchUp(), touchDown(), TouchMove() ,isNaturalRotation(), setRotationRight(), setRotationLeft() ,freezeRotation() ,wakeDevice(), sleepDevice() 等。

QueryController

QueryController负责把UiSelector 的查找信息转化为AccessibilityNodeInfo。
具体Api如下:findNodePatternRecursive(), translatePatternSelector(), translateReqularSelector(), translateCompoundSelector(), getRootNode() ,findAccessibilityNodeInfo()。

UiWatcher

UiWatcher只在UiSelector无法找到匹配的结果时被调用,意在重试、等待页面更新 (如弹出对话框)等。其中只有一个主要函数:checkForCondition() 。

它的相关函数均在UiDevice中,如:UiDevice.registerWatcher() ,UiDevice. resetWatcherTriggers() ,UiDevice.runWatchers() ,UiDevice.removeWatcher()




uiautomator官方参考文档

原文在 http://developer.android.com/tools/help/uiautomator/index.html 。本文对其进行翻译,提供中文版本。关键字:uiautomator使用入门 uiautomator 教程 uiautomator 中文文档

The uiautomator testing framework lets you test your user interface (UI) efficiently by creating automated functional  UI testcases that can be run against your app on one or more devices. For more information on testing with the uiautomator framework, see  UI Testing .

通过使用uiautomator测试框架创建界面的功能测试用例,可以高效在一个或若干安卓设备上测试android应用程序。

Syntax 语法

To run your testcases on the target device, you can use the adb shell command to invoke the uiautomator tool. The syntax is:

为了使测试用例在待测设备上运行,需要使用adb shell命令调用uiautomator工具,语法为:

adb shell uiautomator runtest  < JARS >   - c  < CLASSES >   [ options]

Here’s an example:

例如:

adb shell uiautomator runtest  LaunchSettings . jar  - c com . uia . example . my . LaunchSettings

Command-line Options 命令行选项

The following table describes the subcommands and options for uiautomator.

Table 1. Command-line options for uiautomator

子命令 Option 
选项
Description 
描述
runtest
<JARS>

Required. The <JARS> argument is the name of one or more JAR files that you deployed to the target device which contain your uiautomator testcases. You can list more than one JAR file by using a space as a separator. 
必需。<JARS> 参数指定部署到待测设备上的包含测试用例的jar文件。需要指定多个这样的jar文件时,使用空格进行分割。

-c <CLASSES>

Required (API 17 or lower).The <CLASSES> argument is a list of test classes or test methods in <JARS> to run.

Each class or method must be fully qualified with the package name, in one of these formats:

必需(API 17或更低)。<CLASSES> 参数指定需要运行的<JARS>中的测试类或方法。每个类或方法必须使用全限定名,格式如下:

  • package_name.class_name
  • package_name.class_name#method_name

You can list multiple classes or methods by using a space as a separator. 
使用空格分割多个类或方法。

Note:This argument is not required for API 18 and higher. If not specified, all test cases in <JARS> will be run. API 18时该参数不是必需的,若没有指定,<JARS>中的全部测试用例都会被执行。

–nohup

Runs the test to completion on the device even if its parent process is terminated (for example, if the device is disconnected) .在待测设备上运行测试直至结束,即使测试程序的父进程终止,如设备连接中断,也会执行完测试程序。

-e <NAME> <VALUE>

Specify other name-value pairs to be passed to test classes. May be repeated. 指定传递给测试类的键值对参数,可以重复。

Note: The -e options cannot be combined; you must prefix each option with a separate -e flag. 要指定多个键值对时,每个键值对都需要-e标识。

-e debug [true|false]

Wait for debugger to connect before starting. 在开发执行测试时,是否等待调试器连接。

dump [file]

Generate an XML file with a dump of the current UI hierarchy. If a filepath is not specified, by default, the generated dump file is stored on the device in this location/storage/sdcard0/window_dump.xml. 把当前UI界面阶层树生成到一个XML文件中。如无路径指定,默认生成到 /storage/sdcard0/window_dump.xml

-e outputFormat simple | -s

Enables less verbose JUnit style output. 采用简明的JUnit类型的输出

events
Prints out accessibility events to the console until the connection to the device is terminated控制台输出可访问性事件直至设备连接断开。

The uiautomator API is bundled in the uiautomator.jar file under the <android-sdk>/platforms/ directory. The API includes  these key classes, interfaces, and exceptions that allow you to capture and manipulate UI components on the target app:

uiautomator API包含在目录 <android-sdk>/platforms/下的uiautomator.jar文件中。那些API包括主要的类、接口和异常,可以用来定位 和操作待测应用上的UI控件。


Classes Uiautomator类

Class  类名 Description  描述

com.android.uiautomator.core.UiCollection

Used to enumerate a container’s user interface (UI) elements for the purpose of counting, or targeting a sub

elements by a child’s text or description. 用来枚举界面容器的界面元素,可以统计子元素数量、或者使用文本

或描述定位子元素。

com.android.uiautomator.core.UiDevice

Provides access to state information about the device. You can also use this class to simulate user actions on the device,

such as pressing the d-pad hardware button or pressing the Home and Menu buttons. 对外提供访问设备状态信息的方

法。还能使用该类模拟用户在设备上的动作,如按方向键按钮、或主页键、菜单键。

com.android.uiautomator.core.UiObject

Represents a user interface (UI) element.  代表界面元素。

com.android.uiautomator.core.UiScrollable

Provides support for searching for items in a scrollable UI container. 提供支持查询在可滑动的界面容器中的界面元素

com.android.uiautomator.core.UiSelector

Represents a query for one or more target UI elements on a device screen. 代表在设备屏幕上查询一个或若干界面元

素的查询方法。

com.android.uiautomator.core.Configurator

Allows you to set key parameters for running uiautomator tests. 运行uiautomator测试程序时设置主要的参数。

Interfaces Uiautomator接口

Interface  接口 Description  描述

com.android.uiautomator.core.UiWatcher

Represents a conditional watcher on the target device.

代表待测设备上的条件监听器

com.android.uiautomator.testrunner.IAutomationSupport

Provides auxiliary support for running test cases.

提供运行测试的辅助支持

com.android.uiautomator.testrunner.UiAutomatorTestCase

Defines an environment for running multiple tests. All uiautomator test cases should extend this class.

定义运行多个测试用例时的环境。所有的uiautomator测试用例都需要集成该类。

Exceptions Uiautomator异常

Exception  异常 Description  描述

com.android.uiautomator.core.UiObjectNotFoundException

Indicates when a a  UiSelector  could not be matched to any UI element displayed.

UiSelector 不匹配当前屏幕的界面元素时,抛出异常。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值