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

Android 自動化測試入門:用 AS 2.2 的 Record Espresso 錄製 UI 測試

編輯:關於 Android 程式設計

讓開發好的 App 自己跑一遍測試流程,是不是很酷?那麼,透過在螢幕上點幾下就自動生成測試代碼,是不是更酷?本文借助 Android Studio 2.2 的 Record Espresso 功能,示範如何低成本完成 UI 自動化測試。

一、環境準備

示例代碼已上傳 GitHub,歡迎 star / fork:
https://github.com/shf981862482/AutoTextApplication

在 app 模組的 build.gradle 中指定測試運行器:

android {
    defaultConfig {
        testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
    }
}

加入 packagingOptions 解決資源衝突,否則會報:

Duplicate files copied in APK META-INF/maven/com.google.guava/guava/pom.properties

android {
    packagingOptions {
        pickFirst('META-INF/maven/com.google.guava/guava/pom.xml')
        pickFirst('META-INF/maven/com.google.guava/guava/pom.properties')
    }
}

添加測試依賴:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test:rules:0.5'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
}

再解決 support-annotations 版本衝突,否則會看到:

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

configurations.all {
    resolutionStrategy.force 'com.android.support:support-annotations:23.1.0'
}

另一種等價做法是在依賴中排除該模組:

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

二、必備工具:uiautomatorviewer

先找到你的 SDK 目錄,例如 C:\AndroidSDK\tools,雙擊打開 uiautomatorviewer.bat。

uiautomatorviewer 提供了一個直觀的方式查看 UI 佈局結構,並能讀取各控件的相關屬性,這些資訊正是編寫 UI 測試代碼的關鍵依據。

使用方法:用 USB 連接手機,點擊左上角圖標抓取當前畫面。

選中某個控件(比如 button),右側的 Node Detail 面板會列出 resource-id、content-desc、text、hint 等信息——後續的 Record Espresso 就是靠這些屬性來定位控件。

為了讓自動化測試順利找到控件,開發時建議遵守幾條約定:

1. 為 ImageButton、ImageView、CheckBox 等控件設置 android:contentDescription 標籤。
2. 用 android:hint 標記 EditText,而不是依賴裡面的文本(文本用戶可以改)。
3. 承擔視覺回饋作用的 UI 元素(文本或圖標)都加上 android:hint 以便識別。
4. 確保所有可交互元素都能被方向鍵選中。
5. 用 uiautomatorviewer 驗證每個 UI 元素都能被測試工具訪問;也可以在「設置 → 無障礙」中透過 TalkBack 等服務檢查可訪問性。

三、用 Record Espresso 自動生成測試

在 Android Studio 中依次打開 Record Espresso 入口:

兩步之後會進入如下界面:

這時不要在電腦上點任何按鈕,拿起手機開始操作。示例應用的流程是:

· LauchActivity:模擬耗時初始化
· LoginActivity:輸入用戶名密碼,點擊按鈕後進入 MainActivity

注意,這相當於 debug 模式運行,速度會比較慢:

可以看到,我在手機上輸入用戶名和密碼後,左側就自動生成了對應的測試代碼。點擊登陸按鈕進入 MainActivity:

點擊 Complete Recording 結束錄製,真正生成測試類:

打開生成的 LauchActivityTest,若有亂碼按情況改成中文即可:

四、修正生成出來的測試代碼

先直接編譯運行看看:

此時很可能出現類似這樣的錯誤:

// at dalvik.system.VMStack.getThreadStackTrace(Native Method) ...

它的含義是「找不到這個控件」。原因不難推斷:LauchActivity 中存在耗時初始化操作,而我們的 EditText 屬於 LoginActivity。App 此時還停留在 LauchActivity,測試線程卻已經在 LoginActivity 的時間段裡找控件,自然撲空。

解法是等 LoginActivity 真正啟動後再查找:

Instrumentation.ActivityMonitor am =
        new Instrumentation.ActivityMonitor("sun.com.autotextapplication.LoginActivity", null, false);
getInstrumentation().addMonitor(am);
getInstrumentation().waitForMonitor(am);

如果場景裡還有動畫,佈局要等動畫播完才出現,那就只能讓測試線程先睡一會兒:

try {
    Thread.sleep(2000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

修改後的完整測試方法:

@Test
public void lauchActivityTest() {
    // 等待 LoginActivity 啟動
    Instrumentation.ActivityMonitor am =
            new Instrumentation.ActivityMonitor("sun.com.autotextapplication.LoginActivity", null, false);
    getInstrumentation().addMonitor(am);
    getInstrumentation().waitForMonitor(am);

    ViewInteraction appCompatEditText = onView(
            allOf(withId(R.id.etxt_name),
                  withParent(allOf(withId(R.id.activity_login),
                                 withParent(withId(android.R.id.content)))),
                  isDisplayed()));
    appCompatEditText.perform(click());

    ViewInteraction appCompatEditText2 = onView(
            allOf(withId(R.id.etxt_name),
                  withParent(allOf(withId(R.id.activity_login),
                                 withParent(withId(android.R.id.content)))),
                  isDisplayed()));
    appCompatEditText2.perform(replaceText("hong"));

    ViewInteraction appCompatEditText5 = onView(
            allOf(withId(R.id.etxt_pass),
                  withParent(allOf(withId(R.id.activity_login),
                                 withParent(withId(android.R.id.content)))),
                  isDisplayed()));
    appCompatEditText5.perform(replaceText("123"));

    ViewInteraction appCompatButton = onView(
            allOf(withId(R.id.btn_login), withText("登陸"),
                  withParent(allOf(withId(R.id.activity_login),
                                 withParent(withId(android.R.id.content)))),
                  isDisplayed()));
    appCompatButton.perform(click());

    // 等待 MainActivity 啟動,並留出動畫時間
    Instrumentation.ActivityMonitor amMain =
            new Instrumentation.ActivityMonitor("sun.com.autotextapplication.MainActivity", null, false);
    getInstrumentation().addMonitor(amMain);
    getInstrumentation().waitForMonitor(amMain);
    try {
        Thread.sleep(20000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

大功告成,執行測試:

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