Android自動化測試--UI Automator使用

上一篇文章:
Android自動化測試--Espresso使用

相比上一篇文章所講的Espresso使用,本文所講的自動化測試UI Automator最顯著的特點就是,可以與多個app進行交互。

UI Automator 能夠運行在 Android 4.3 (API 18) ?及以上的版本。

使用

首先我們在Android Studio中新建一個項目,取名為UIAutomatorTests。同時刪除自動生成的一些文件,最終目錄結構如下:

Paste_Image.png

接下來我們看看如何一步一步的使用Espresso,首先在?根目錄的 build.gradle 文件中添加下面的引入。

ext {
    buildToolsVersion = "24.0.1"
    supportLibVersion = "24.2.0"
    uiautomatorVersion = "2.1.1"
    runnerVersion = "0.5"
    rulesVersion = "0.5"
}

在app目錄中的build.gradle 文件中添加下面的引入,根據提示點擊Sync Now。

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    // App dependencies
    compile 'com.android.support:appcompat-v7:' + rootProject.supportLibVersion;
    compile 'com.android.support:support-annotations:' + rootProject.supportLibVersion;
    androidTestCompile 'com.android.support:support-annotations:' + rootProject.supportLibVersion;
    androidTestCompile 'com.android.support.test:runner:' + rootProject.runnerVersion;
    // UiAutomator Testing
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:' + rootProject.uiautomatorVersion;
    androidTestCompile 'org.hamcrest:hamcrest-integration:1.3'
}

接下來我們在AutomatorTest.class中編寫測試代碼,為了測試多個app,這里我們選擇上篇文章中的EspressoTests和手機中的設置app。

Paste_Image.png

在EspressoTests中我們輸入數據點擊計算,然后通過設置app為手機更換一個一個鈴聲。詳細的測試代碼如下:

package me.shihao.uiautomatortests;

import android.content.Context;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SdkSuppress;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.support.test.uiautomator.Until;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.*;

@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion = 18)
public class AutomatorTest {

    private static final String PACKAGE_ESPRESSOTESTS = "me.shihao.espressotests";
    private static final String PACKAGE_SETTING = "com.android.settings";

    @Test
    public void testEspressoTestsApp() throws Exception {
        //初始化一個UiDevice對象
        UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        // 點擊home鍵,回到home界面
        mDevice.pressHome();
        String launcherPackage = mDevice.getLauncherPackageName();
        assertThat(launcherPackage, notNullValue());
        mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), 3);

        // 啟動espressotests App
        Context context = InstrumentationRegistry.getContext();
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(PACKAGE_ESPRESSOTESTS);
        // 清除以前的實例
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);

        // 等待應用程序啟動
        mDevice.wait(Until.hasObject(By.pkg(PACKAGE_ESPRESSOTESTS).depth(0)), 3);
        //通過id找到輸入框一
        UiObject edt1 = mDevice.findObject(new UiSelector().resourceId("me.shihao.espressotests:id/editText")
            .className(EditText.class));
        //往里面輸入字符2
        edt1.setText("2");
        //通過id找到輸入框二
        UiObject edt2 = mDevice.findObject(new UiSelector().resourceId("me.shihao.espressotests:id/editText2")
            .className(EditText.class));
        //往里面輸入5
        edt2.setText("5");
        //通過文本"計算"找到按鈕
        UiObject btn = mDevice.findObject(new UiSelector().text("計算").className(Button.class));
        //執行點擊事件,計算結果
        btn.click();
        //通過id找到顯示結果的textview
        UiObject tvResult = mDevice.findObject(new UiSelector().resourceId("me.shihao.espressotests:id/textView")
            .className(TextView.class));
        //判斷結果與預期是否匹配
        assertEquals(tvResult.getText(), "計算結果:7");
        //通過文本"RecycleView"找到按鈕
        UiObject btnRecycleView = mDevice.findObject(new UiSelector().text("RecycleView").className(Button.class));
        //執行點擊事件跳轉到另一個界面
        btnRecycleView.click();
        //通過id找到recycleview
        UiScrollable recycleview = new UiScrollable(new UiSelector()
            .className(RecyclerView.class)
            .resourceId("me.shihao.espressotests:id/recycleview"));
        //滑動到底部
        recycleview.flingForward();
        //滑動到頂部
        recycleview.flingBackward();
        UiObject item5 = recycleview.getChild(new UiSelector().text("Item 5"));
        //點擊Item 5,然后會彈出一個對話框
        item5.click();
        //通過文本"確定"找到對話框中的確定按鈕
        UiObject btnConfirm = mDevice.findObject(new UiSelector().text("確定").className(Button.class));
        //點擊確定關閉對話框
        btnConfirm.click();
        //另外一種方式找到Item 2
        UiObject item = mDevice.findObject(new UiSelector()
            .className(RecyclerView.class)
            .resourceId("me.shihao.espressotests:id/recycleview")
            .childSelector(new UiSelector().text("Item 2")));
        //點擊彈出對話框
        item.click();
        //點擊返回關閉對話框
        mDevice.pressBack();
    }


    @Test
    public void testSettingApp() throws Exception {
        //初始化一個UiDevice對象
        Context context = InstrumentationRegistry.getContext();
        UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        //回到home界面
        mDevice.pressHome();
        // 啟動設置
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(PACKAGE_SETTING);
        // 清除以前的實例
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
        //通過id找到scrollview
        UiScrollable scrollview = new UiScrollable(new UiSelector().className(ScrollView.class).resourceId("com" +
            ".android.settings:id/dashboard"));
        //滑動到底部
        scrollview.flingForward();
        //通過文本找到關于手機
        UiObject aboutPhone = scrollview.getChild(new UiSelector().text("關于手機"));
        //點擊跳轉到手機信息界面
        aboutPhone.click();
        //通過description找到向上返回的ImageButton
        UiObject ibtnBack = mDevice.findObject(new UiSelector().className(ImageButton.class).description("向上導航"));
        //點擊返回
        ibtnBack.click();
        //滑動到包含"提示音和通知"的地方
        scrollview.scrollTextIntoView("提示音和通知");
        //通過顯示的文本找到控件
        UiObject notify = scrollview.getChild(new UiSelector().text("提示音和通知"));
        //點擊跳轉到下一個界面
        notify.click();
        //通過顯示的文本"手機鈴聲"找到控件
        UiObject sound = mDevice.findObject(new UiSelector().text("手機鈴聲"));
        //點擊跳轉到鈴聲對話框
        sound.click();
        //通過id找到鈴聲列表
        UiScrollable listview = new UiScrollable(new UiSelector().className(ListView.class).resourceId
            ("android:id/select_dialog_listview"));
        //活動到包含"Beat Plucker"處
       listview.scrollTextIntoView("Beat Plucker");
        //通過顯示的文本找到該項
        UiObject beat = listview.getChild(new UiSelector().text("Beat Plucker"));
        //執行點擊選中鈴聲
        beat.click();
        //通過文本"確定"找到對話框中的確定按鈕
        UiObject btnConfirm = mDevice.findObject(new UiSelector().text("確定").className(Button.class));
        //點擊確定關閉對話框
        btnConfirm.click();
        //通過id找到顯示結果的TextView
        UiObject tvSound = mDevice.findObject(new UiSelector().resourceId("android:id/summary").className(TextView
            .class));
        //比較與預期結果是否一致
        assertEquals(tvSound.getText(), "Beat Plucker");
        //點擊home鍵
        mDevice.pressHome();
        //點擊最近應用鍵
        mDevice.pressRecentApps();
        //通過類名找到顯示最近app的控件TaskStackView
        UiScrollable taskStackView = new UiScrollable(new UiSelector().className("com.android.systemui.recents.views" +
            ".TaskStackView"));
        //滑動到包含"EspressoTests"處
        taskStackView.scrollTextIntoView("EspressoTests");
        //通過顯示的文本找到item
        UiObject espressoTestsApp = taskStackView.getChild(new UiSelector().text("EspressoTests"));
        //點擊切換到前面的espressoTestsApp
        espressoTestsApp.click();
    }
}

運行效果如下:

運行效果.gif
運行效果.gif

UI Automator Viewer使用

從上面的測試代碼可以看到,我們需要首先知道目標控件的一些屬性值,然后再圍繞我們的目標屬性構建一個匹配規則。?而實際中我們并不知道app的實現,控件的屬性并不是那么明顯,或者并沒有那么容易獲取到,這時,我們可以使用Android提供的uiautomatorviewer工具幫助我們進行分析。

接下來我們就講一下如何使用,Android Studio中點擊Tools >> Android >> Android Device Monitor


Paste_Image.png

下面顯示的就是界面,最左邊會顯示連接的設備


Paste_Image.png

點擊會截圖分析設備當前顯示界面布局
Paste_Image.png

然后右邊會顯示布局結構以及view詳細的信息。

Paste_Image.png

在實際使用中,我用了幾個真機測試都會報這個錯誤
Error obtaining UI hierarchy Error while obtaining UI hierarchy XML file: com.android.ddmlib.SyncException: Remote object doesn't exist!,也一直沒找到原因,到后面使用Genymotion并不會出現這個問題,有知道的小伙伴,可以告訴我,一定非常感謝。

Paste_Image.png

接下來我們就看一看如何使用壓力測試,歡迎查看下一篇文章:

Android自動化測試--Monkey使用

Demo代碼已經放到了Github上:https://github.com/fodroid/UIAutomatorTests

如果你覺得有用,請在Github不吝給我一個Star,非常感謝。


寫在最后的話:個人能力有限,歡迎大家在下面吐槽。喜歡的話就為我點一個贊吧。也歡迎 Fork Me On Github 。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,619評論 6 539
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,155評論 3 425
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,635評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,539評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,255評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,646評論 1 326
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,655評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,838評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,399評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,146評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,338評論 1 372
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,893評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,565評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,983評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,257評論 1 292
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,059評論 3 397
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,296評論 2 376

推薦閱讀更多精彩內容