【Espresso】withText

/**
   * Returns a matcher that matches {@link TextView}s based on text property value.
   *
   * <p><b>Note:</b> A View text property is never {@code null}. If you call {@link
   * TextView#setText(CharSequence)} with a {@code null} value it will still be "" (empty string).
   * Do not use a null matcher.
   *
   * @param stringMatcher <a
   *     href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matcher.html"><code>Matcher
   *     </code></a> of {@link String} with text to match
   */
  public static Matcher<View> withText(final Matcher<String> stringMatcher) {
    return new WithTextMatcher(checkNotNull(stringMatcher));
  }

由上述註釋可知,該方法適用於TextView,所以使用onData時不能使用這條屬性,即不能像下面那樣調用

onData(withText("item1"));

它可以與onView配合使用,withText返回的是一個WithTextMatcher類型,WithTextMatcher繼承自BoundedMatcher,重寫了BoundedMatcher的一些方法,其中matchesSafely方法如下:

@Override
    protected boolean matchesSafely(TextView textView) {
      String text = textView.getText().toString();
      // The reason we try to match both original text and the transformated one is because some UI
      // elements may inherit a default theme which behave differently for SDK below 19 and above.
      // So it is implemented in a backwards compatible way.
      if (stringMatcher.matches(text)) {
        return true;
      } else if (textView.getTransformationMethod() != null) {
        CharSequence transformedText =
            textView.getTransformationMethod().getTransformation(text, textView);
        if (transformedText != null) {
          return stringMatcher.matches(transformedText.toString());
        }
      }
      return false;
    }

由此可見,withText最終找到的對象必須是TextView類型的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章