Android UIAutomator淺談
[TOC]
簡介
Uiautomator是谷歌推出的笋粟,用于UI自動(dòng)化測(cè)試的工具践樱,也就是普通的手工測(cè)試她奥,點(diǎn)擊每個(gè)控件元素看看輸出的結(jié)果是否符合預(yù)期泌辫。比如登陸界面分別輸入正確和錯(cuò)誤的用戶名密碼然后點(diǎn)擊登陸按鈕看看是否能否登陸以及是否有錯(cuò)誤提示等叉跛。
注意:UI Automator測(cè)試框架是基于instrumentation的API阳堕,運(yùn)行在Android JunitRunner 之上跋理,同時(shí)UI Automator Test只運(yùn)行在Android 4.3(API level 18)以上版本。
準(zhǔn)備
集成UI Automator恬总,首先需要保證App項(xiàng)目已經(jīng)依賴了Gradle Testing前普。然后在gradle中添加如下依賴即可。
dependencies {
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'
}
UI元素查找
在Android開發(fā)中壹堰,可以種findViewById來找到相應(yīng)的控件拭卿,但是UI Automator是用來測(cè)試界面的,如果也是用相同的方式贱纠,那么則會(huì)依賴很大峻厚。UI Automator使用一種類似的方式來查找元素。UI Automator是根據(jù)元素的text谆焊、hint惠桃、contentDescription等屬性進(jìn)行查找的,為了使UI Automator能夠獲取到以上的屬性值辖试,請(qǐng)測(cè)試的UI界面是可以訪問的辜王,同時(shí)UI Automator也是可以訪問這些控件元素。
可以使用uiautomatorviewer剃执,來獲取界面元素的層次關(guān)系以及各個(gè)元素的屬性誓禁,然后UI Automator就可以根據(jù)這些屬性信息查找到對(duì)應(yīng)的控件元素懈息。
獲取步驟:
- 啟動(dòng)設(shè)備上的App
- 把設(shè)備連接到開發(fā)機(jī)器上
- 打開Android sdk目錄肾档,
<android-sdk>/tools/
。 - 啟動(dòng)
uiautomatorviewer
然后可以操作uiautomatorviewer
- 點(diǎn)擊Device ScreenShot,稍等一會(huì)怒见,獲取到了屏幕的快照俗慈,界面右側(cè)是當(dāng)前界面的布局結(jié)構(gòu)以及屬性信息。
確保UI可以訪問
上面介紹過遣耍,UI Automator是根據(jù)元素的text闺阱、hint、contentDescription等屬性進(jìn)行查找的舵变,所以需要盡可能給布局中的元素添加上面的屬性酣溃。有時(shí)候程序員需要自定義一些控件,那么請(qǐng)實(shí)現(xiàn)AccessibilityNodeProvider
纪隙,以確鄙尥悖可以正常使用。
訪問UI控件
UI Automator 提供 UiDevice
類绵咱,這個(gè)類提供一些方法碘饼,可以獲取設(shè)備的一些狀態(tài)和屬性,同時(shí)可以執(zhí)行一系列動(dòng)作來操作設(shè)備悲伶。下面是一個(gè)示例艾恼,演示怎么樣貨到 UiDevice 對(duì)象,以及按下Home鍵麸锉。
import org.junit.Before;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.Until;
...
@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion = 18)
public class ChangeTextBehaviorTest {
private static final String BASIC_SAMPLE_PACKAGE
= "com.example.android.testing.uiautomator.BasicSample";
private static final int LAUNCH_TIMEOUT = 5000;
private static final String STRING_TO_BE_TYPED = "UiAutomator";
private UiDevice mDevice;
@Before
public void startMainActivityFromHomeScreen() {
// Initialize UiDevice instance
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
// Start from the home screen
mDevice.pressHome();
// Wait for launcher
final String launcherPackage = mDevice.getLauncherPackageName();
assertThat(launcherPackage, notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
LAUNCH_TIMEOUT);
// Launch the app
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager()
.getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE);
// Clear out any previous instances
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
// Wait for the app to appear
mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)),
LAUNCH_TIMEOUT);
}
}
然后可以使用findObject()
方法來獲取到界面的UI控件钠绍,如下所示,在一個(gè)設(shè)備上面找出符合規(guī)則的UI元素淮椰,然后再執(zhí)行一些列動(dòng)作五慈。
UiObject cancelButton = mDevice.findObject(new UiSelector()
.text("Cancel"))
.className("android.widget.Button"));
UiObject okButton = mDevice.findObject(new UiSelector()
.text("OK"))
.className("android.widget.Button"));
// Simulate a user-click on the OK button, if found.
if(okButton.exists() && okButton.isEnabled()) {
okButton.click();
}
指定一個(gè)選擇器
有時(shí)候,需要訪問一個(gè)特定的UI組件主穗,可以使用UiSelector
泻拦。這個(gè)類提供一些列的方法,幫助找到特定的UI組件忽媒。
當(dāng)有多個(gè)符合條件UI元素被查找到時(shí)候争拐,第一個(gè)元素會(huì)不是使用』抻辏可以傳遞的一個(gè)UiSelector到構(gòu)造方法架曹,相當(dāng)于鏈?zhǔn)皆L問。如果沒有元素被找到闹瞧,那么會(huì)拋出UiAutomatorObjectNotFoundException
異常绑雄。
也可以使用childSelector()
來帥選多個(gè)UiSelector對(duì)象,如下所示奥邮,ListView的子元素中有很多是相同的万牺,可以根據(jù)這個(gè)方法罗珍,選擇某一個(gè)子元素。
UiObject appItem = new UiObject(new UiSelector()
.className("android.widget.ListView")
.instance(1)
.childSelector(new UiSelector()
.text("Apps")));
上面的查找還是很復(fù)雜脚粟,我們可以根據(jù)ResourceId 來替代文本查找的方式覆旱。文本找到的方式很脆弱,而且很容使測(cè)試失敗核无,而且當(dāng)語言環(huán)境變化了扣唱,文本查找就需要對(duì)照多個(gè)翻譯版本的文本了。
執(zhí)行動(dòng)作
當(dāng)我們根據(jù)文本查找找到對(duì)應(yīng)的文本元素后团南,我們就可以隨心所欲的進(jìn)行操作了噪沙。
- click() 點(diǎn)擊
- dragTo() 拖動(dòng)當(dāng)前元素
- setText() 設(shè)置文本
- swipeUp() 向上滑動(dòng),同理也有向下吐根、向左曲聂、向右,swipeDown佑惠、swipeLeft朋腋、swipeRight。
UI Automator也可以提供一個(gè)Context膜楷,這樣可以方便發(fā)送一個(gè)Intent或者是啟動(dòng)一個(gè)Activity旭咽。
public void setUp() {
// Launch a simple calculator app
Context context = getInstrumentation().getContext();
Intent intent = context.getPackageManager()
.getLaunchIntentForPackage(CALC_PACKAGE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Clear out any previous instances
context.startActivity(intent);
mDevice.wait(Until.hasObject(By.pkg(CALC_PACKAGE).depth(0)), TIMEOUT);
}
集合操作
可以使用UiCollection
來模擬用戶對(duì)一組UI控件進(jìn)行操作,比如有時(shí)候界面上有個(gè)Listview赌厅。為了創(chuàng)建一個(gè) UiCollection 對(duì)象穷绵,可以指定一個(gè)UiSelector搜索這個(gè)UI容器上滿足這個(gè)條件的所有子元素。
下面代碼演示如何在一個(gè)一組控件中進(jìn)行操作特愿。
UiCollection videos = new UiCollection(new UiSelector()
.className("android.widget.FrameLayout"));
// Retrieve the number of videos in this collection:
int count = videos.getChildCount(new UiSelector()
.className("android.widget.LinearLayout"));
// Find a specific video and simulate a user-click on it
UiObject video = videos.getChildByText(new UiSelector()
.className("android.widget.LinearLayout"), "Cute Baby Laughing");
video.click();
// Simulate selecting a checkbox that is associated with the video
UiObject checkBox = video.getChild(new UiSelector()
.className("android.widget.Checkbox"));
if(!checkBox.isSelected()) checkbox.click();
操作可以滾動(dòng)的UI元素
可以使用UiScrollable
來模擬用戶對(duì)界面的滾動(dòng)操作(水平仲墨、垂直),這個(gè)技術(shù)可以幫我們搞定,當(dāng)某個(gè)界面沒有顯示的時(shí)候揍障,我們可以滾動(dòng)界面目养,把那個(gè)界面顯示出來。
UiScrollable settingsItem = new UiScrollable(new UiSelector()
.className("android.widget.ListView"));
UiObject about = settingsItem.getChildByText(new UiSelector()
.className("android.widget.LinearLayout"), "About tablet");
about.click();
校驗(yàn)結(jié)果
Ui Automator 是基于InstrumentationTestCase毒嫡,同樣InstrumentationTestCase是基于標(biāo)準(zhǔn)的JUnit Assert癌蚁,那么我們也可以使用標(biāo)準(zhǔn)的JUnit Assert來判斷結(jié)果。
下面代碼片段演示一個(gè)計(jì)算器的代碼兜畸,以及驗(yàn)證結(jié)果努释。
private static final String CALC_PACKAGE = "com.myexample.calc";
public void testTwoPlusThreeEqualsFive() {
// Enter an equation: 2 + 3 = ?
mDevice.findObject(new UiSelector()
.packageName(CALC_PACKAGE).resourceId("two")).click();
mDevice.findObject(new UiSelector()
.packageName(CALC_PACKAGE).resourceId("plus")).click();
mDevice.findObject(new UiSelector()
.packageName(CALC_PACKAGE).resourceId("three")).click();
mDevice.findObject(new UiSelector()
.packageName(CALC_PACKAGE).resourceId("equals")).click();
// Verify the result = 5
UiObject result = mDevice.findObject(By.res(CALC_PACKAGE, "result"));
assertEquals("5", result.getText());
}
Api
UiDevice
void clearLastTraversedText()
// Clears the text from the last UI traversal event.
// 清楚上次UI遍歷的事件?
boolean click(int x, int y)
// Perform a click at arbitrary coordinates specified by the user
// 根據(jù)坐標(biāo)點(diǎn)擊
boolean drag(int startX, int startY, int endX, int endY, int steps)
// Performs a swipe from one coordinate to another coordinate.
// 拖動(dòng)
void dumpWindowHierarchy(File dest)
// Dump the current window hierarchy to a File.
// dump當(dāng)前的層次化結(jié)構(gòu)到文件中
void dumpWindowHierarchy(OutputStream out)
// Dump the current window hierarchy to an OutputStream.
// dump當(dāng)前的層次化結(jié)構(gòu)到流中
void dumpWindowHierarchy(String fileName)
// This method is deprecated. Use dumpWindowHierarchy(File) or dumpWindowHierarchy(OutputStream) instead.
// dump當(dāng)前的層次化結(jié)構(gòu)到文件中
UiObject2 findObject(BySelector selector)
// Returns the first object to match the selector criteria.
// 根據(jù)BySelector查找
UiObject findObject(UiSelector selector)
// Returns a UiObject which represents a view that matches the specified selector criteria.
// 根據(jù)UiSelector 查找
List<UiObject2> findObjects(BySelector selector)
// Returns all objects that match the selector criteria.
// 根據(jù)BySelector查找
void freezeRotation()
// Disables the sensors and freezes the device rotation at its current rotation state.
// 凍結(jié)旋轉(zhuǎn)的狀態(tài)
String getCurrentActivityName()
// This method is deprecated. The results returned should be considered unreliable
// 獲取當(dāng)前Activity的名字咬摇,已經(jīng)被廢棄
String getCurrentPackageName()
// Retrieves the name of the last package to report accessibility events.
// 獲取當(dāng)前package
int getDisplayHeight()
// Gets the height of the display, in pixels.
int getDisplayRotation()
// Returns the current rotation of the display, as defined in Surface
Point getDisplaySizeDp()
// Returns the display size in dp (device-independent pixel) The returned display size is adjusted per screen rotation.
int getDisplayWidth()
// Gets the width of the display, in pixels.
static UiDevice getInstance()
// This method is deprecated. Should use getInstance(Instrumentation) instead. This version hides UiDevice's dependency on having an Instrumentation reference and is prone to misuse.
// 獲取一個(gè)對(duì)象
static UiDevice getInstance(Instrumentation instrumentation)
// Retrieves a singleton instance of UiDevice
String getLastTraversedText()
// Retrieves the text from the last UI traversal event received.
// 獲取上一次遍歷的文本
String getLauncherPackageName()
// Retrieves default launcher package name
// 獲取運(yùn)行的packagename
String getProductName()
// Retrieves the product name of the device.
boolean hasAnyWatcherTriggered()
// Checks if any registered UiWatcher have triggered.
// 檢查是否有觸發(fā)器觸發(fā)
boolean hasObject(BySelector selector)
// Returns whether there is a match for the given selector criteria.
// 是否有符合的條件的
boolean hasWatcherTriggered(String watcherName)
// Checks if a specific registered UiWatcher has triggered.
boolean isNaturalOrientation()
// Check if the device is in its natural orientation.
boolean isScreenOn()
// Checks the power manager if the screen is ON.
boolean openNotification()
// Opens the notification shade.
// 打開通知
boolean openQuickSettings()
// Opens the Quick Settings shade.
// 打開設(shè)置
<R> R performActionAndWait(Runnable action, EventCondition<R> condition, long timeout)
// Performs the provided action and waits for the condition to be met.
boolean pressBack()
// Simulates a short press on the BACK button.
boolean pressDPadCenter()
// Simulates a short press on the CENTER button.
boolean pressDPadDown()
// Simulates a short press on the DOWN button.
boolean pressDPadLeft()
// Simulates a short press on the LEFT button.
boolean pressDPadRight()
// Simulates a short press on the RIGHT button.
boolean pressDPadUp()
// Simulates a short press on the UP button.
boolean pressDelete()
// Simulates a short press on the DELETE key.
boolean pressEnter()
// Simulates a short press on the ENTER key.
boolean pressHome()
// Simulates a short press on the HOME button.
boolean pressKeyCode(int keyCode)
// Simulates a short press using a key code.
boolean pressKeyCode(int keyCode, int metaState)
// Simulates a short press using a key code.
boolean pressMenu()
// Simulates a short press on the MENU button.
boolean pressRecentApps()
// Simulates a short press on the Recent Apps button.
boolean pressSearch()
// Simulates a short press on the SEARCH button.
void registerWatcher(String name, UiWatcher watcher)
// Registers a UiWatcher to run automatically when the testing framework is unable to find a match using a UiSelector.
void removeWatcher(String name)
// Removes a previously registered UiWatcher.
void resetWatcherTriggers()
// Resets a UiWatcher that has been triggered.
void runWatchers()
// This method forces all registered watchers to run.
void setCompressedLayoutHeirarchy(boolean compressed)
// Enables or disables layout hierarchy compression.
void setOrientationLeft()
// Simulates orienting the device to the left and also freezes rotation by disabling the sensors.
// 設(shè)置旋轉(zhuǎn)方向
void setOrientationNatural()
// Simulates orienting the device into its natural orientation and also freezes rotation by disabling the sensors.
void setOrientationRight()
// Simulates orienting the device to the right and also freezes rotation by disabling the sensors.
void sleep()
// This method simply presses the power button if the screen is ON else it does nothing if the screen is already OFF.
// 關(guān)閉屏幕
boolean swipe(int startX, int startY, int endX, int endY, int steps)
// Performs a swipe from one coordinate to another using the number of steps to determine smoothness and speed.
boolean swipe(Point[] segments, int segmentSteps)
// Performs a swipe between points in the Point array.
boolean takeScreenshot(File storePath, float scale, int quality)
// Take a screenshot of current window and store it as PNG The screenshot is adjusted per screen rotation
// 截屏
boolean takeScreenshot(File storePath)
// Take a screenshot of current window and store it as PNG Default scale of 1.0f (original size) and 90% quality is used The screenshot is adjusted per screen rotation
void unfreezeRotation()
// Re-enables the sensors and un-freezes the device rotation allowing its contents to rotate with the device physical rotation.
<R> R wait(SearchCondition<R> condition, long timeout)
// Waits for given the condition to be met.
void waitForIdle(long timeout)
// Waits for the current application to idle.
void waitForIdle()
// Waits for the current application to idle.
boolean waitForWindowUpdate(String packageName, long timeout)
// Waits for a window content update event to occur.
void wakeUp()
// This method simulates pressing the power button if the screen is OFF else it does nothing if the screen is already ON.
// 點(diǎn)亮屏幕
UiObject
void clearTextField()
// Clears the existing text contents in an editable field.
// 清空輸入接口
boolean click()
// Performs a click at the center of the visible bounds of the UI element represented by this UiObject.
// 點(diǎn)擊
boolean clickAndWaitForNewWindow()
// Waits for window transitions that would typically take longer than the usual default timeouts.
// 點(diǎn)擊并等待新界面
boolean clickAndWaitForNewWindow(long timeout)
// Performs a click at the center of the visible bounds of the UI element represented by this UiObject and waits for window transitions.
// 點(diǎn)擊并等待新界面伐蒂,設(shè)置等待時(shí)間
boolean clickBottomRight()
// Clicks the bottom and right corner of the UI element
// 點(diǎn)擊右下邊
boolean clickTopLeft()
// Clicks the top and left corner of the UI element
boolean dragTo(UiObject destObj, int steps)
// Drags this object to a destination UiObject.
// 拖動(dòng)
boolean dragTo(int destX, int destY, int steps)
// Drags this object to arbitrary coordinates.
boolean exists()
// Check if view exists.
// 判斷是否存在
Rect getBounds()
// Returns the view's bounds property.
// 返回邊界
UiObject getChild(UiSelector selector)
// Creates a new UiObject for a child view that is under the present UiObject.
// 根據(jù)條件獲取子元素
int getChildCount()
// Counts the child views immediately under the present UiObject.
// 獲取子元素?cái)?shù)量
String getClassName()
// Retrieves the className property of the UI element.
// 獲取當(dāng)前元素的class name
String getContentDescription()
// Reads the content_desc property of the UI element
UiObject getFromParent(UiSelector selector)
// Creates a new UiObject for a sibling view or a child of the sibling view, relative to the present UiObject.
String getPackageName()
// Reads the view's package property
final UiSelector getSelector()
// Debugging helper.
String getText()
// Reads the text property of the UI element
Rect getVisibleBounds()
// Returns the visible bounds of the view.
// 獲取可見邊界
boolean isCheckable()
// Checks if the UI element's checkable property is currently true.
// 是否可以點(diǎn)擊
boolean isChecked()
// Check if the UI element's checked property is currently true
// 是否已經(jīng)選中
boolean isClickable()
// Checks if the UI element's clickable property is currently true.
boolean isEnabled()
// Checks if the UI element's enabled property is currently true.
boolean isFocusable()
// Check if the UI element's focusable property is currently true.
boolean isFocused()
// Check if the UI element's focused property is currently true
boolean isLongClickable()
// Check if the view's long-clickable property is currently true
boolean isScrollable()
// Check if the view's scrollable property is currently true
boolean isSelected()
// Checks if the UI element's selected property is currently true.
boolean longClick()
// Long clicks the center of the visible bounds of the UI element
// 長按
boolean longClickBottomRight()
// Long clicks bottom and right corner of the UI element
boolean longClickTopLeft()
// Long clicks on the top and left corner of the UI element
boolean performMultiPointerGesture(PointerCoords... touches)
// Performs a multi-touch gesture.
boolean performTwoPointerGesture(Point startPoint1, Point startPoint2, Point endPoint1, Point endPoint2, int steps)
// Generates a two-pointer gesture with arbitrary starting and ending points.
boolean pinchIn(int percent, int steps)
// Performs a two-pointer gesture, where each pointer moves diagonally toward the other, from the edges to the center of this UiObject .
boolean pinchOut(int percent, int steps)
// Performs a two-pointer gesture, where each pointer moves diagonally opposite across the other, from the center out towards the edges of the this UiObject.
boolean setText(String text)
// Sets the text in an editable field, after clearing the field's content.
// 設(shè)置輸入內(nèi)容
boolean swipeDown(int steps)
// Performs the swipe down action on the UiObject.
boolean swipeLeft(int steps)
// Performs the swipe left action on the UiObject.
boolean swipeRight(int steps)
// Performs the swipe right action on the UiObject.
boolean swipeUp(int steps)
// Performs the swipe up action on the UiObject.
boolean waitForExists(long timeout)
// Waits a specified length of time for a view to become visible.
boolean waitUntilGone(long timeout)
// Waits a specified length of time for a view to become undetectable.
總結(jié)
優(yōu)點(diǎn):
- 可以對(duì)所有操作進(jìn)行自動(dòng)化,操作簡單
- 不需要對(duì)被測(cè)程序進(jìn)行重簽名肛鹏,且逸邦,可以測(cè)試所有設(shè)備上的程序汰翠,比如某APP,比如撥號(hào)昭雌,比如~發(fā)信息等等
- 對(duì)于控件定位,要比robotium簡單一點(diǎn)點(diǎn)
缺點(diǎn):
- Ui Automator需要android level 16以上才可以使用健田,因?yàn)樵趌evel 16及以上的API里面才帶有uiautomator工具
- 如果想要使用resource-id定位控件烛卧,則需要level 18及以上才可以
- 對(duì)中文支持不好(不代表不支持,第三方j(luò)ar可以實(shí)現(xiàn))
鏈接
https://developer.android.com/training/testing/ui-testing/uiautomator-testing.html``