Android自动化测试-从入门到入门(4)uiautomatorviewer

uhhj0129 8年前

来自: https://segmentfault.com/a/1190000004367222


我们用如下一行代码来回顾一下之前介绍过的内容:

import static android.support.test.espresso.Espresso.onView;  import static android.support.test.espresso.action.ViewActions.click;  import static android.support.test.espresso.assertion.ViewAssertions.matches;  import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;  import static android.support.test.espresso.matcher.ViewMatchers.withId;  import static android.support.test.espresso.matcher.ViewMatchers.withText;  import static org.hamcrest.Matchers.allOf;    onView(allOf(withId(id), isDisplayed())).perform(click()).check(matches(withText(text)));

还记得以上代码的意义么?这行代码找到了屏幕上正在显示的指定id的控件,对其进行了一次点击操作,然后检查了一下其文本为text

关于onView()方法,我们需要首先知道目标控件的一些属性值,然后再围绕我们的目标属性构建一个匹配规则。但有些时候,控件的属性并不是那么明显,或者并没有那么容易获取到,这时,我们可以使用Android提供的uiautomatorviewer工具帮助我们进行分析。

uiautomatorviewer

uiautomatorviewer工具位于Android SDK目录下,本文会介绍在Mac下uiautomatorviewer的用法,其他系统下的用法相当雷同,就不一一介绍了。

在终端中切换到Android SDK的目录下,在tools目录下可以看到uiautomatorviewer工具:

运行./uiautomatorviewer,便可以看到uiautomatorviewer的主界面了:

很朴素对不对~

屏幕截图

将手机连接到设备上,在手机上启动一个需要测试的目标页面,然后点击uiautomatorviewer左上角的第二个按钮(Device Screenshot(uiautomator dump)),便可以把当前页面截下来了:

如上所示,我截取了一张答疑君APP登录页面的截图。可以看到,uiautomatorviewer的界面分成了3个部分:

  • 左边部分:显示当前屏幕的截图。在这个部分,我们可以对这个页面上的各个控件做一些选中的操作。

  • 右上角部分:显示当前页面的View层级。

  • 右下角部分:显示当前选中控件的各个属性。

比如说,我现在想要做一个登录的测试用例,我需要在“账号”和“密码” 的输入框中输入一些内容,然后点击“登录”按钮执行登录。首先,我选中填写账号的EditText

大家可以看到,右上角的View层级自动定位到了我选中的EditText上,同时右下角显示了这个EditText的一些属性信息。其中,resource-id便是这个EditTextid,于是我通过:

onView(withId(R.id.login_account))

便找到了这个EditText。然后,向这个EditText中输入账号信息:

onView(withId(R.id.login_account)).perform(click(), replaceText("..."), closeSoftKeyboard())

就完成了一个表单的输入。

类似地,我们还可以通过text的属性来寻找我们的目标控件。我们可以根据属性区域显示的text来进行匹配:

onView(withText("账号"))

小总结

Android所提供的uiautomatorviewer界面简单,使用方便,对于我们的自动化测试来说是一个很好的辅助工具。对于我们之后将要介绍的UI Automator,以及第三方测试框架Appium,都离不开这个小工具的支持。于是,请大家赶快操练起来吧~

附录

从这篇开始,我会在每一篇的最后附上本系列的所有文章传送门,方便大家进行查阅:

Android自动化测试-从入门到入门(1) Hello Testing!
Android自动化测试-从入门到入门(2) Testing APIs
Android自动化测试-从入门到入门(3) Espresso入门
Android自动化测试-从入门到入门(4) uiautomatorviewer
Android自动化测试-从入门到入门(5) AdapterView的测试