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阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容