espresso-api之Matchers探究

通过前3篇文章,大家应该对espresso有了大体上的了解,那么今天我们要深入了解它的API,看看espresso的整体架构。
还是通过espresso cheat sheet来进入本次话题。

Espresso备忘单是您在开发过程中可以使用的快速参考。 这个备忘单包含大多数可用的Matchers,ViewActions和ViewAsertions。
让我们先来看看Matchers 都有哪些API可供我们使用。

android.support.test.espresso.matcher
Classes
BoundedMatcher<T, S extends T>  Some matcher sugar that lets you create a matcher for a given type but only process items of a specific subtype of that matcher.
CursorMatchers  A collection of Hamcrest matchers that matches a data row in a Cursor.
CursorMatchers.CursorMatcher    A Matcher that matches Cursors based on values in their columns.
LayoutMatchers  A collection of hamcrest matches to detect typical layout issues.
PreferenceMatchers  A collection of hamcrest matchers that match Preferences.
RootMatchers    A collection of matchers for Root objects.
ViewMatchers    A collection of hamcrest matchers that match Views.
Enums
ViewMatchers.Visibility Enumerates the possible list of values for View.getVisibility().

7个类,1个Eums。接下来我们一个个欣赏谷歌大神的杰作。

BoundedMatcher
一些匹配语法糖,允许您为给定类型创建匹配器,但只能处理该匹配器的特定子类型项。换句话说,就是能够自定义一些匹配器。
举个栗子,以下是一个自定义错误文本匹配器


public final class ErrorTextMatchers {

  /**
   * Returns a matcher that matches {@link TextView}s based on text property value.
   *
   * @param stringMatcher {@link Matcher} of {@link String} with text to match
   */
  @NonNull
  public static Matcher<View> withErrorText(final Matcher<String> stringMatcher) {

    return new BoundedMatcher<View, TextView>(TextView.class) {

      @Override
      public void describeTo(final Description description) {
        description.appendText("with error text: ");
        stringMatcher.describeTo(description);
      }

      @Override
      public boolean matchesSafely(final TextView textView) {
        return stringMatcher.matches(textView.getError().toString());
      }
    };
  }
}

实现的主要细节如下。 我们通过从withErrorText()返回一个BoundedMatcher来确保匹配器只匹配TextView类的子类。 这使得很容易在BoundedMatcher.matchesSafely()中实现匹配逻辑本身:只需从TextView中获取getError()方法并将其送入下一个匹配器。 最后,我们有一个简单的describeTo()方法的实现,它只用于生成调试输出到控制台。

CursorMatchers

Hamcrest的集合匹配器,在Cursor匹配相应的数据行。
源码如下


/**
   * Returns a matcher that matches a {@link String} value at a given column index
   * in a {@link Cursor}s data row.
   * <br>
   * @param columnIndex int column index
   * @param value a {@link String} value to match
   */
  public static CursorMatcher withRowString(int columnIndex, String value) {
    return withRowString(columnIndex, is(value));
  }

大部分的场景,大多发生于表单或者滚动menu时。


onData(
    is(instanceOf(Cursor.class)),
    CursorMatchers.withRowString("job_title", is("Barista"))
);

LayoutMatchers hamcrest的集合匹配以检测典型的布局问题。
例如匹配具有椭圆形文本的TextView元素。 如果文本太长,无法适应TextView,
它可以是椭圆形(’Too long’显示为’Too l …’或’… long’)或切断(’Too
long“显示为”Too l“)。 虽然在某些情况下可以接受,但通常表示不好的用户体验。

PreferenceMatchers hamcrest匹配器来匹配一组偏好。
Preference组件其实就是Android常见UI组件与SharePreferences的组合封装实现。

onData(Matchers.<Object>allOf(PreferenceMatchers.withKey("setting-name"))).perform(click());

PreferenceMatchers还有以下方法可以应用到其他场景


withSummary(final int resourceId)
withSummaryText(String summary)
withSummaryText(final Matcher<String> summaryMatcher)
withTitle(final int resourceId)
withTitleText(String title)
withTitleText(final Matcher<String> titleMatcher)
isEnabled()

RootMatchers Root对象的匹配器集合。
匹配root装饰视图匹配给定的视图匹配器。


onView(withText("Text"))
  .inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView()))))
  .perform(click());

RootMatchers还有以下方法可以应用到其他场景

Public methods
static Matcher  isDialog()Matches Roots that are dialogs (i.e.)
static Matcher  isFocusable()Matches Roots that can take window focus.
static Matcher  isPlatformPopup()Matches Roots that are popups - like autocomplete suggestions or the actionbar spinner.
static Matcher  isTouchable()Matches Roots that can receive touch events.
static Matcher  withDecorView(Matcher decorViewMatcher)Matches Roots with decor views that match the given view matcher.

ViewMatchers 最重要也是应用最广的匹配器,通过一个或者多个来定位层级里面的控件。

Public methods
static void assertThat(String message, T actual, Matcher matcher) A replacement for MatcherAssert.assertThat that renders View objects nicely.
static void assertThat(T actual, Matcher matcher) A replacement for MatcherAssert.assertThat that renders View objects nicely.
static Matcher  hasContentDescription() Returns an Matcher that matches Views with any content description.
static Matcher  hasDescendant(Matcher descendantMatcher) Returns a matcher that matches Views based on the presence of a descendant in its view hierarchy.
static Matcher  hasErrorText(String expectedError) Returns a matcher that matches EditText based on edit text error string value.
static Matcher  hasErrorText(Matcher stringMatcher) Returns a matcher that matches EditText based on edit text error string value.
static Matcher  hasFocus() Returns a matcher that matches Views currently have focus.
static Matcher  hasImeAction(int imeAction) Returns a matcher that matches views that support input methods (e.g.
static Matcher  hasImeAction(Matcher imeActionMatcher) Returns a matcher that matches views that support input methods (e.g.
static Matcher  hasLinks() Returns a matcher that matches TextViews that have links.
static Matcher  hasSibling(Matcher siblingMatcher) Returns an Matcher that matches Views based on their siblings.
static Matcher  isAssignableFrom(Class<? extends View> clazz) Returns a matcher that matches Views which are an instance of or subclass of the provided class.
static Matcher  isChecked() Returns a matcher that accepts if and only if the view is a CompoundButton (or subtype of) and is in checked state.
static Matcher  isClickable() Returns a matcher that matches Views that are clickable.
static Matcher  isCompletelyDisplayed() Returns a matcher which only accepts a view whose height and width fit perfectly within the currently displayed region of this view.
static Matcher  isDescendantOfA(Matcher ancestorMatcher) Returns a matcher that matches Views based on the given ancestor type.
static Matcher  isDisplayed() Returns a matcher that matches Views that are currently displayed on the screen to the user.
static Matcher  isDisplayingAtLeast(int areaPercentage) Returns a matcher which accepts a view so long as a given percentage of that view’s area is not obscured by any other view and is thus visible to the user.
static Matcher  isEnabled() Returns a matcher that matches Views that are enabled.
static Matcher  isFocusable() Returns a matcher that matches Views that are focusable.
static Matcher  isJavascriptEnabled() Returns a matcher that matches WebView if they are evaluating Javascript.
static Matcher  isNotChecked() Returns a matcher that accepts if and only if the view is a CompoundButton (or subtype of) and is not in checked state.
static Matcher  isRoot() Returns a matcher that matches root View.
static Matcher  isSelected() Returns a matcher that matches Views that are selected.
static Matcher  supportsInputMethods() Returns a matcher that matches views that support input methods.
static Matcher  withChild(Matcher childMatcher) A matcher that returns true if and only if the view’s child is accepted by the provided matcher.
static Matcher  withClassName(Matcher classNameMatcher) Returns a matcher that matches Views with class name matching the given matcher.
static Matcher  withContentDescription(int resourceId) Returns a Matcher that matches Views based on content description property value.
static Matcher  withContentDescription(String text) Returns an Matcher that matches Views based on content description property value.
static Matcher  withContentDescription(Matcher<? extends CharSequence> charSequenceMatcher) Returns an Matcher that matches Views based on content description property value.
static Matcher  withEffectiveVisibility(ViewMatchers.Visibility visibility) Returns a matcher that matches Views that have “effective” visibility set to the given value.
static Matcher  withHint(Matcher stringMatcher) Returns a matcher that matches TextViews based on hint property value.
static Matcher  withHint(int resourceId) Returns a matcher that matches a descendant of TextView that is displaying the hint associated with the given resource id.
static Matcher  withHint(String hintText) Returns a matcher that matches TextView based on it’s hint property value.
static Matcher  withId(Matcher integerMatcher) Returns a matcher that matches Views based on resource ids.
static Matcher  withId(int id) Same as withId(is(int)), but attempts to look up resource name of the given id and use an R.id.myView style description with describeTo.
static Matcher  withInputType(int inputType) Returns a matcher that matches InputType.
static Matcher  withParent(Matcher parentMatcher) A matcher that accepts a view if and only if the view’s parent is accepted by the provided matcher.
static Matcher  withResourceName(String name) Returns a matcher that matches Views based on resource id names, (for instance, channel_avatar).
static Matcher  withResourceName(Matcher stringMatcher) Returns a matcher that matches Views based on resource id names, (for instance, channel_avatar).
static Matcher  withSpinnerText(int resourceId) Returns a matcher that matches a descendant of Spinner that is displaying the string of the selected item associated with the given resource id.
static Matcher  withSpinnerText(String text) Returns a matcher that matches Spinner based on it’s selected item’s toString value.
static Matcher  withSpinnerText(Matcher stringMatcher) Returns a matcher that matches Spinners based on toString value of the selected item.
static Matcher  withTagKey(int key) Returns a matcher that matches View based on tag keys.
static Matcher  withTagKey(int key, Matcher objectMatcher) Returns a matcher that matches Views based on tag keys.
static Matcher  withTagValue(Matcher tagValueMatcher) Returns a matcher that matches Views based on tag property values.
static Matcher  withText(Matcher stringMatcher) Returns a matcher that matches TextViews based on text property value.
static Matcher  withText(String text) Returns a matcher that matches TextView based on its text property value.
static Matcher  withText(int resourceId) Returns a matcher that matches a descendant of TextView that is displaying the string associated with the given resource id.

ok 这次主要介绍Matchers的API 更多的内容 大家还是要查看官方API去学习。
最新内容请见作者的GitHub页:http://qaseven.github.io/

时间: 2025-01-21 06:03:24

espresso-api之Matchers探究的相关文章

espresso系列一简介

espresso是什么? Espresso 测试框架提供了一系列的API用于构建UI测试来测试app内用户流操作.这些API让你可以编写简洁可靠的自动化UI测试.Espresso非常适合用来编写白盒测试,其中测试代码的编写是利用了被测试app中程序代码实现细节. Espresso测试可运行android 2.3.3(API 10 level)以及更高版本的设备上.使用Espresso的主要好处是,当你运行测试时它提供了自动的同步测试动作与应用程序UI.Espresso会检测你的主线程是否为空闲状

2014非常好用的开源Android测试工具

当前有很大的趋势是转向移动应用平台,Android 是最广泛使用的移动操作系统,2014 年大约占 80% 以上的市场.在开发 Android 应用的时候要进行测试,现在市场上有大量的测试工具. 本文主要是展示一系列的开源 Android 测试工具.每个工具都会有相应的简短介绍,还有一些相关的资源.Android 测试工具列表是按照字母来排序的,最后还会介绍几个不是特别活跃的 Android 测试相关的开源项目. 本文提到的开源 Android 软件测试工具包括:Android Test Kit

2014 非常好用的开源 Android 测试工具

当前有很大的趋势是转向移动应用平台,Android 是最广泛使用的移动操作系统,2014 年大约占 80% 以上的市场.在开发 Android 应用的时候要进行测试,现在市场上有大量的测试工具. 本文主要是展示一系列的开源 Android 测试工具.每个工具都会有相应的简短介绍,还有一些相关的资源.Android 测试工具列表是按照字母来排序的,最后还会介绍几个不是特别活跃的 Android 测试相关的开源项目. 本文提到的开源 Android 软件测试工具包括:Android Test Kit

JavaScript的胜利

还记得曾几何时,不少朋友出于安全性考虑而选择在自己的浏览器上禁用JavaScript.时至今日,这种作法已经变得荒谬可笑--理由很简单, JavaScript已经统治了整个网络世界.在这个充斥着平台多样性的全新计算时代,我们需要那些能够运行在任意设备浏览器中的应用程序.原生应用可能运行速度更快.调用更多JavaScript 无法染指的特定平台功能,但不可否认,云时代已然来临.我们则身处其中.有鉴于此,我们要继续坚持针对专一平台编写桌面或者移动应用.还是拓宽思路利用 JavaScript开发一些任

espresso基础架构与API分析

Espresso测试框架提供了一组API来构建UI测试,以测试应用程序内的用户流. 这些API让您能够编写简洁,运行可靠的自动化UI测试. Espresso非常适合编写白盒式自动化测试,其中测试代码使用来自所测试的应用程序的实现代码细节. Espresso测试框架的主要功能包括: 用于在目标应用程序中查看和适配器匹配的灵活API. 有关详细信息,请参阅View matching. 一组广泛的操作API,用于自动化UI交互. 有关更多信息,请参阅 Action APIs. UI线程同步提高测试的可

借助JArchitect探究Cassandra CLI内部机制

关系型数据库管理系统(RDBMS)是存储和使用数据最常用的系统,但对于超 大量数据,这些数据库的扩展性不是很好. 近年来,由于对关系型数据库替代产品的需求日益增长,NoSQL的概念已经受 到广泛的欢迎.NoSQL背后的最大动机是可扩展性.NoSQL数据库解决方案提供了 一种存储和使用超大量数据的方法,而且开销更小,工作量更少,性能更好,停 机时间更短. Apache Cassandra是一个基于列的NoSQL数据库.它是Facebook为推动其收件 箱搜索功能而开发的,后来成为Apache的开源

ASP.NET Web API具有Windows Azure AD和MS OWIN 组件的安全ASP.NET Web API

随着 Web API 角色的重要性日益增加,在可能暴露敏感数据和操作的高价值方案中确保能够信心十足地 使用 Web API 的需求也愈加迫切. 我们可以清楚地看到,整个行业都在寻找一种解决方案,以便为依赖 OAuth 2.0 标准的 REST API 提供 保护.但在实践中,关于应该在项目层面上做些什么,并没有提供详细的指导.此外,Microsoft .NET Framework 中用于保护通信的现有类和工具设计用于特定应用程序类型(基于回发的 Web UX 应用程序). 它们不适用于 Web

探究Lotus Forms中的事件处理,第二部分

XForm表单对函数和事件处理功能的支持 Lotus Forms 通过构建动态的电子表单,收集用户信息并将其传递给其他应用系统,以实现业务流程的管理.与纸质表单相比,XForm 电子表单的最大优势之一就是能够动态地响应用户活动.如,根据用户输入动态改变背景颜色,响应鼠标点击事件发送邮件或提交表单,等等.本文将通过若干实例,向您详细讲述 Lotus Forms 中的事件处理机制 , 包括 XForm 表单支持的主要事件.活动和函数.通过本文的讲述,您将能够灵活自如地使用 Lotus Forms D

React Native Android 应用内存使用探究

本文讲的是React Native Android 应用内存使用探究, 为什么我那台老旧的 Android 手机无法加载图片? 刚开始接触 React Native 应用时,我发现有个现象很奇怪,在 Android 手机上我无法看到任何图片,只有颜色和文字可以显示.但 iOS 手机却没有任何问题. 我以为是我新找来测试 React Native 工程的 Android 手机有问题.我甚至被这错误的想法牵着刷了 rom (基于 AOSP 5.1.1 的系统)来在更高的 Android 版本上运行