Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Studio 實測 UI Automator:從依賴設定到第一支測試

編輯:關於 Android 程式設計

UI Automator 是 Android 官方提供的跨應用 UI 測試框架,它能夠模擬使用者在裝置上的操作,也能讀取目前畫面上的元件資訊,適合用來寫「打開某個 App、點擊某顆按鈕、驗證結果」這類端到端測試。本文記錄在 Android Studio 中把 UI Automator 跑起來的完整過程。

一、安裝 Android Support Repository

UI Automator 以 Support Library 的形式發布,因此必須先透過 SDK Manager 安裝 Android Support Repository,否則後續在 build.gradle 中加入依賴時會找不到套件。

二、最低版本要求

minSdkVersion 18

三、加入 UI Automator 依賴

在 Module 層級的 build.gradle 中宣告對 UI Automator 的依賴。注意它屬於 androidTestCompile,也就是只會被打進測試 APK,不會進入正式版:

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.1.0'
    testCompile 'junit:junit:4.12'

    // UI Automator
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.0'
}

四、準備一個待測功能

先寫一個最簡單的 demo:畫面上有一個 TextView 和一顆 Button,每按一次按鈕,文字就累加一次點擊次數。這樣後續測試就有明確的驗證目標。

版面配置 activity_main.xml:

<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="app.test.myapplication.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_marginStart="14dp"
        android:text="Button" />

</RelativeLayout>

Activity 程式碼:

private int clicks = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView textView = (TextView) findViewById(R.id.textView);

    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            textView.setText("click: " + clicks);
            clicks++;
        }
    });
}

五、撰寫測試案例

在 androidTest 資料夾底下新增測試類別。

測試程式碼:

public class MainTest extends UiAutomatorTestCase {

    public void testMain() throws UiObjectNotFoundException {

        // 以系統計算機為例的操作示範(已註解)
        // getUiDevice().pressHome();
        // UiObject Calculator = new UiObject(new UiSelector().description("計算器"));
        // Calculator.clickAndWaitForNewWindow();
        // UiObject seven = new UiObject(new UiSelector().resourceId("com.android.calculator2:id/digit7"));
        // seven.click();
        // UiObject plus = new UiObject(new UiSelector().resourceId("com.android.calculator2:id/plus"));
        // plus.click();
        // UiObject one = new UiObject(new UiSelector().resourceId("com.android.calculator2:id/digit1"));
        // one.click();
        // UiObject result = new UiObject(new UiSelector().resourceId("com.android.calculator2:id/equal"));
        // result.click();
        // getUiDevice().pressBack();

        getUiDevice().pressHome();

        Context context = InstrumentationRegistry.getContext();
        Intent launchIntent = new Intent();
        launchIntent.setComponent(new ComponentName(
                "app.test.myapplication", "app.test.myapplication.MainActivity"));
        context.startActivity(launchIntent);

        UiObject main = new UiObject(new UiSelector()
                .resourceId("app.test.myapplication:id/button"));
        main.click();
    }
}

六、幾個實務上的提醒

第一,UiAutomatorTestCase 是舊版 API 的用法。若採用 uiautomator-v18:2.1.0 這一代的函式庫,建議改用 UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) 取得裝置物件,測試類別則以 JUnit 的方式撰寫,不再需要繼承 UiAutomatorTestCase。

第二,UiSelector 的定位順序建議優先使用 resourceId,其次才是 text 或 description。resourceId 穩定度最高,而文字很容易因為多語言或文案調整而失效。

第三,UI Automator 只能「看到」目前畫面上的元件,無法存取元件背後的內部狀態。若需要更精細的介面驗證,可以搭配 Espresso 一起使用。

七、常見錯誤

如果執行時出現 UiObjectNotFoundException,通常代表定位條件寫錯,或者目標元件所在的頁面還沒切換過去。建議先在測試中插入 getUiDevice().wait() 或 UiObject2.waitForExists(),確保畫面已經就緒再操作。

更多說明可參考官方文件中的 UI Automator 章節。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved