本文档介绍了如何使用 Espresso API 完成常见的自动化测试任务。
Espresso API 鼓励测试作者从用户与应用交互的角度思考——定位 UI 元素并与之交互。同时,该框架会阻止直接访问应用的 Activity 和 View,因为持有这些对象并在 UI 线程外对其进行操作是测试不稳定的主要来源。因此,您不会在 Espresso API 中看到诸如 getView()
和 getCurrentActivity()
等方法。您仍然可以通过实现自己的 ViewAction
和 ViewAssertion
子类来安全地操作 View。
API 组件
Espresso 的主要组件包括:
- Espresso – 与视图交互的入口点(通过
onView()
和onData()
)。还公开了不一定与任何视图绑定的 API,例如pressBack()
。 - ViewMatchers – 实现
Matcher<? super View>
接口的对象集合。您可以将其中一个或多个传递给onView()
方法,以在当前视图层次结构中定位视图。 - ViewActions – 可传递给
ViewInteraction.perform()
方法的ViewAction
对象集合,例如click()
。 - ViewAssertions – 可传递给
ViewInteraction.check()
方法的ViewAssertion
对象集合。大多数情况下,您将使用 matches 断言,它使用 View 匹配器来断言当前选定视图的状态。
示例
Kotlin
// withId(R.id.my_view) is a ViewMatcher // click() is a ViewAction // matches(isDisplayed()) is a ViewAssertion onView(withId(R.id.my_view)) .perform(click()) .check(matches(isDisplayed()))
Java
// withId(R.id.my_view) is a ViewMatcher // click() is a ViewAction // matches(isDisplayed()) is a ViewAssertion onView(withId(R.id.my_view)) .perform(click()) .check(matches(isDisplayed()));
查找视图
在绝大多数情况下,onView()
方法接受一个 Hamcrest 匹配器,该匹配器应匹配当前视图层次结构中的一个(且仅一个)视图。匹配器功能强大,对于那些在 Mockito 或 JUnit 中使用过它们的人来说会很熟悉。如果您不熟悉 Hamcrest 匹配器,建议您先快速查看此演示文稿。
通常,所需的视图具有唯一的 R.id
,简单的 withId
匹配器将缩小视图搜索范围。但是,在测试开发时无法确定 R.id
的合法情况有很多。例如,特定视图可能没有 R.id
,或者 R.id
不唯一。这使得正常的仪器化测试变得脆弱且难以编写,因为访问视图的常规方式(使用 findViewById()
)不起作用。因此,您可能需要访问持有视图的 Activity 或 Fragment 的私有成员,或者找到一个具有已知 R.id
的容器并导航到其内容以查找特定视图。
Espresso 通过允许您使用现有 ViewMatcher
对象或您自己的自定义对象来缩小视图范围,从而清晰地解决了这个问题。
通过视图的 R.id
查找视图就像调用 onView()
一样简单
Kotlin
onView(withId(R.id.my_view))
Java
onView(withId(R.id.my_view));
有时,R.id
值在多个视图之间共享。发生这种情况时,尝试使用特定的 R.id
会抛出异常,例如 AmbiguousViewMatcherException
。异常消息会提供当前视图层次结构的文本表示,您可以搜索并找到与非唯一 R.id
匹配的视图。
java.lang.RuntimeException: androidx.test.espresso.AmbiguousViewMatcherException This matcher matches multiple views in the hierarchy: (withId: is <123456789>) ... +----->SomeView{id=123456789, res-name=plus_one_standard_ann_button, visibility=VISIBLE, width=523, height=48, has-focus=false, has-focusable=true, window-focus=true, is-focused=false, is-focusable=false, enabled=true, selected=false, is-layout-requested=false, text=, root-is-layout-requested=false, x=0.0, y=625.0, child-count=1} ****MATCHES**** | +------>OtherView{id=123456789, res-name=plus_one_standard_ann_button, visibility=VISIBLE, width=523, height=48, has-focus=false, has-focusable=true, window-focus=true, is-focused=false, is-focusable=true, enabled=true, selected=false, is-layout-requested=false, text=Hello!, root-is-layout-requested=false, x=0.0, y=0.0, child-count=1} ****MATCHES****
查看视图的各种属性,您可能会发现唯一可识别的属性。在上面的示例中,其中一个视图的文本是 "Hello!"
。您可以使用它通过组合匹配器来缩小搜索范围
Kotlin
onView(allOf(withId(R.id.my_view), withText("Hello!")))
Java
onView(allOf(withId(R.id.my_view), withText("Hello!")));
您也可以选择不反转任何匹配器
Kotlin
onView(allOf(withId(R.id.my_view), not(withText("Unwanted"))))
Java
onView(allOf(withId(R.id.my_view), not(withText("Unwanted"))));
有关 Espresso 提供的视图匹配器,请参阅 ViewMatchers
。
注意事项
- 在行为良好的应用中,用户可以与之交互的所有视图都应包含描述性文本或内容描述。有关更多详细信息,请参阅使应用更易于访问。如果您无法使用
withText()
或withContentDescription()
缩小搜索范围,请考虑将其视为无障碍功能错误。 - 使用最不具描述性的匹配器来查找您要查找的视图。不要过度指定,因为这会迫使框架做不必要的工作。例如,如果一个视图可以通过其文本唯一识别,则您无需指定该视图也可以从
TextView
分配。对于许多视图,视图的R.id
应该足够了。 - 如果目标视图位于
AdapterView
(例如ListView
、GridView
或Spinner
)内,则onView()
方法可能不起作用。在这些情况下,您应该改用onData()
。
对视图执行操作
当您找到了目标视图的合适匹配器后,可以使用 perform 方法对其执行 ViewAction
实例。
例如,要点击视图
Kotlin
onView(...).perform(click())
Java
onView(...).perform(click());
您可以通过一次 perform 调用执行多个操作
Kotlin
onView(...).perform(typeText("Hello"), click())
Java
onView(...).perform(typeText("Hello"), click());
如果您正在使用的视图位于 ScrollView
(垂直或水平)内,请考虑在需要显示视图的操作(例如 click()
和 typeText()
)之前加上 scrollTo()
。这确保了在进行其他操作之前显示视图。
Kotlin
onView(...).perform(scrollTo(), click())
Java
onView(...).perform(scrollTo(), click());
有关 Espresso 提供的视图操作,请参阅 ViewActions
。
检查视图断言
可以使用 check()
方法将断言应用于当前选定的视图。最常用的断言是 matches()
断言。它使用 ViewMatcher
对象来断言当前选定视图的状态。
例如,要检查视图是否具有文本 "Hello!"
Kotlin
onView(...).check(matches(withText("Hello!")))
Java
onView(...).check(matches(withText("Hello!")));
如果您想断言 "Hello!"
是视图的内容,则以下做法被视为不良做法
Kotlin
// Don't use assertions like withText inside onView. onView(allOf(withId(...), withText("Hello!"))).check(matches(isDisplayed()))
Java
// Don't use assertions like withText inside onView. onView(allOf(withId(...), withText("Hello!"))).check(matches(isDisplayed()));
另一方面,如果您想断言具有文本 "Hello!"
的视图是可见的——例如在视图可见性标志更改后——则代码是正确的。
视图断言简单测试
在此示例中,SimpleActivity
包含一个 Button
和一个 TextView
。当按钮被点击时,TextView
的内容会更改为 "Hello Espresso!"
。
以下是如何使用 Espresso 进行测试的方法
点击按钮
第一步是寻找有助于找到按钮的属性。SimpleActivity
中的按钮具有唯一的 R.id
,正如预期。
Kotlin
onView(withId(R.id.button_simple))
Java
onView(withId(R.id.button_simple));
现在执行点击
Kotlin
onView(withId(R.id.button_simple)).perform(click())
Java
onView(withId(R.id.button_simple)).perform(click());
验证 TextView 文本
要验证文本的 TextView
也具有唯一的 R.id
Kotlin
onView(withId(R.id.text_simple))
Java
onView(withId(R.id.text_simple));
现在验证内容文本
Kotlin
onView(withId(R.id.text_simple)).check(matches(withText("Hello Espresso!")))
Java
onView(withId(R.id.text_simple)).check(matches(withText("Hello Espresso!")));
检查适配器视图中的数据加载
AdapterView
是一种特殊的微件类型,它从适配器动态加载数据。AdapterView
最常见的示例是 ListView
。与 LinearLayout
等静态微件不同,只有 AdapterView
的子集可以加载到当前视图层次结构中。简单的 onView()
搜索不会找到当前未加载的视图。
Espresso 通过提供一个单独的 onData()
入口点来处理这个问题,该入口点能够首先加载相关适配器项,使其获得焦点,然后再对其或其任何子项进行操作。
警告:如果 AdapterView
的自定义实现违反了继承契约,特别是 getItem()
API,则可能导致 onData()
方法出现问题。在这种情况下,最佳做法是重构您的应用代码。如果无法做到这一点,您可以实现匹配的自定义 AdapterViewProtocol
。有关更多信息,请查看 Espresso 提供的默认 AdapterViewProtocols
类。
适配器视图简单测试
这个简单的测试演示了如何使用 onData()
。SimpleActivity
包含一个带有几种咖啡饮料类型的 Spinner
。当选择一个项时,TextView
会变为 "One %s a day!"
,其中 %s
代表所选的项。
此测试的目标是打开 Spinner
,选择一个特定的项,并验证 TextView
是否包含该项。由于 Spinner
类基于 AdapterView
,因此建议使用 onData()
而不是 onView()
来匹配该项。
打开项目选择
Kotlin
onView(withId(R.id.spinner_simple)).perform(click())
Java
onView(withId(R.id.spinner_simple)).perform(click());
选择一个项目
对于项目选择,Spinner
会创建一个包含其内容的 ListView
。这个视图可能很长,并且元素可能不会添加到视图层次结构中。通过使用 onData()
,我们强制将所需的元素放入视图层次结构中。Spinner
中的项目是字符串,因此我们要匹配一个等于字符串 "Americano"
的项目
Kotlin
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Americano"))).perform(click())
Java
onData(allOf(is(instanceOf(String.class)), is("Americano"))).perform(click());
验证文本是否正确
Kotlin
onView(withId(R.id.spinnertext_simple)) .check(matches(withText(containsString("Americano"))))
Java
onView(withId(R.id.spinnertext_simple)) .check(matches(withText(containsString("Americano"))));
调试
当测试失败时,Espresso 会提供有用的调试信息
日志记录
Espresso 将所有视图操作记录到 logcat。例如
ViewInteraction: Performing 'single click' action on view with text: Espresso
视图层次结构
当 onView()
失败时,Espresso 会在异常消息中打印视图层次结构。
- 如果
onView()
未找到目标视图,则会抛出NoMatchingViewException
。您可以检查异常字符串中的视图层次结构,以分析匹配器未匹配任何视图的原因。 - 如果
onView()
找到多个与给定匹配器匹配的视图,则会抛出AmbiguousViewMatcherException
。视图层次结构会被打印出来,并且所有匹配的视图都会用MATCHES
标签标记。
java.lang.RuntimeException: androidx.test.espresso.AmbiguousViewMatcherException This matcher matches multiple views in the hierarchy: (withId: is <123456789>) ... +----->SomeView{id=123456789, res-name=plus_one_standard_ann_button, visibility=VISIBLE, width=523, height=48, has-focus=false, has-focusable=true, window-focus=true, is-focused=false, is-focusable=false, enabled=true, selected=false, is-layout-requested=false, text=, root-is-layout-requested=false, x=0.0, y=625.0, child-count=1} ****MATCHES**** | +------>OtherView{id=123456789, res-name=plus_one_standard_ann_button, visibility=VISIBLE, width=523, height=48, has-focus=false, has-focusable=true, window-focus=true, is-focused=false, is-focusable=true, enabled=true, selected=false, is-layout-requested=false, text=Hello!, root-is-layout-requested=false, x=0.0, y=0.0, child-count=1} ****MATCHES****
处理复杂的视图层次结构或微件的意外行为时,使用 Android Studio 中的层级查看器总是很有帮助的。
适配器视图警告
Espresso 会警告用户 AdapterView
微件的存在。当 onView()
操作抛出 NoMatchingViewException
并且视图层次结构中存在 AdapterView
微件时,最常见的解决方案是使用 onData()
。异常消息将包含一个警告,其中包含适配器视图的列表。您可以使用此信息调用 onData()
来加载目标视图。
其他资源
有关在 Android 测试中使用 Espresso 的更多信息,请查阅以下资源。
示例
- CustomMatcherSample:展示了如何扩展 Espresso 以匹配
EditText
对象的提示属性。 - RecyclerViewSample:Espresso 的
RecyclerView
操作。 - (更多...)