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 。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容