Android測試工具 UIAutomator入門與介紹
UI Automator 測試工具定義以及用途
UI Automator 測試框架提供了一組 API,用於構建在使用者應用和系統應用上執行互動的介面測試。通過 UI Automator API,您可以執行在測試裝置中開啟“設定”選單或應用啟動器等操作。UI Automator 測試框架非常適合編寫黑盒式自動化測試,此類測試的測試程式碼不依賴於目標應用的內部實現細節。
優點:可以對所有的操作來進行自動化,操作簡單(eg:點選事件 ,側滑事件,上拉事件,以及模擬鍵盤輸入測試用例)。可以測試所有裝置的程式。
缺點:必須要Android4.0以上才能使用。
UI Automator 的執行呢,需要我們編寫完畢打成jar包,直接上傳到/data/local/tmp/ 目錄下面,然後用adb 命令執行即可。由於是安卓原生的,比較穩定,執行的速度也比較快。
我們下載了安卓的環境變數後,然後下載任意大於4.0的安卓版本sdk即可。
都會有這個jar包,我們在寫程式碼,建立工程的時候,直接引入即可。
如何獲取定位呢,我們可以uiautomatorviewer。
UI Automator 測試框架的主要功能包括:
用於檢查佈局層次結構的檢視器。
用於檢索狀態資訊並在目標裝置上執行操作的 API。
支援跨應用介面測試的 API。
UI Automator 測試框架提供了一個 UiDevice 類,用於在執行目標應用的裝置上訪問和執行操作。您可以呼叫其方法以訪問裝置屬性,如當前螢幕方向或顯示屏尺寸。UiDevice 類還可用於執行以下操作:
改變裝置的旋轉。
按硬體鍵,如“音量調高按鈕”。
按返回、主螢幕或選單按鈕。
開啟通知欄。
擷取當前視窗的螢幕截圖。
UI Automator API
通過 UI Automator API,您可以編寫可靠的測試,而無需瞭解目標應用的實現細節。您可以使用這些 API 在多個應用間捕獲和操縱介面元件:
UiCollection:列舉容器的介面元素,目的是為了計數,或者按可見文字或內容說明屬性來定位子元素。
UiObject:表示裝置上可見的介面元素。
UiScrollable:支援搜尋可滾動介面容器中的專案。
UiSelector:表示對裝置上的一個或多個目標介面元素的查詢。
Configurator:可讓您設定用於執行 UI Automator 測試的關鍵引數。
官方文件
https://developer.android.com/reference/androidx/test/uiautomator/package-summary
官方文件有著詳細的介紹
正常的我們加入後,在後可以看到,有什麼類,方式是什麼,裡面有什麼api。
我們可以在引入後檢視。
下面列舉幾個類的方法
UiDevice
void clearLastTraversedText() // 清除上次UI遍歷的事件 boolean click(int x, int y) // 根據座標點選 boolean drag(int startX, int startY, int endX, int endY, int steps) // 拖動 void dumpWindowHierarchy(File dest) // dump當前的層次化結構到檔案中 void dumpWindowHierarchy(OutputStream out) // dump當前的層次化結構到流中 void dumpWindowHierarchy(String fileName) // dump當前的層次化結構到檔案中 UiObject2 findObject(BySelector selector) // 根據BySelector查詢 UiObject findObject(UiSelector selector) // 根據UiSelector 查詢 List<UiObject2> findObjects(BySelector selector) // 根據BySelector查詢 void freezeRotation() // 凍結旋轉的狀態 String getCurrentActivityName() // 獲取當前Activity的名字,已經被廢棄 String getCurrentPackageName() // 獲取當前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() // 獲取一個物件 static UiDevice getInstance(Instrumentation instrumentation) // Retrieves a singleton instance of UiDevice String getLastTraversedText() // 獲取上一次遍歷的文字 String getLauncherPackageName() // 獲取執行的packagename String getProductName() // Retrieves the product name of the device. boolean hasAnyWatcherTriggered() // 檢查是否有觸發器觸發 boolean hasObject(BySelector selector) // 是否有符合的條件的 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() // 開啟設定 <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() // 設定旋轉方向 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() // 關閉螢幕 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) // 截圖 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() // 點亮螢幕
UiObject
void clearTextField() // 清空輸入介面 boolean click() // 點選 boolean clickAndWaitForNewWindow() // 點選並等待新介面 boolean clickAndWaitForNewWindow(long timeout) // 點選並等待新介面,設定等待時間 boolean clickBottomRight() // 點選右下邊 boolean clickTopLeft() // Clicks the top and left corner of the UI element boolean dragTo(UiObject destObj, int steps) // 拖動 boolean dragTo(int destX, int destY, int steps) // Drags this object to arbitrary coordinates. boolean exists() // 判斷是否存在 Rect getBounds() // 返回邊界 UiObject getChild(UiSelector selector) // 根據條件獲取子元素 int getChildCount() // 獲取子元素數量 String getClassName() // 獲取當前元素的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() // 獲取可見邊界 boolean isCheckable() // 是否可以點選 boolean isChecked() // 是否已經選中 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() // 長按 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) // 設定輸入內容 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.
下面給大家展示一個UiAutomator的testcase
package cn.cool; import com.android.uiautomator.testrunner.UiAutomatorTestCase; import android.os.RemoteException; public class Testone extends UiAutomatorTestCase { @Override protected void setUp() throws Exception { super.setUp(); } public void testCool() throws RemoteException, InterruptedException { } @Override protected void tearDown() throws Exception { } }
然後我們可以在實際的專案中,去實現我們真實的業務的程式碼。實現完畢呢, 我們就可以用 adb . shell push cool.jar /data/local/tmp/ 然後使用 adb shell uiautomator runtest cool.jar -c cn.cool.Testone 就可以執行了。uiautomator 由於只能打成jar包,所以它不能直接在編輯器上進行除錯。