自定義檢視匹配器



Espresso 提供了多種選項來建立我們自己的自定義檢視匹配器,它基於 Hamcrest 匹配器。自定義匹配器是一個非常強大的概念,可以擴充套件框架,也可以根據我們的喜好自定義框架。編寫自定義匹配器的一些優點如下:

  • 利用我們自己的自定義檢視的獨特功能

  • 自定義匹配器有助於 AdapterView 基於測試用例匹配不同型別的底層資料。

  • 透過組合多個匹配器的功能來簡化當前的匹配器

我們可以根據需要建立新的匹配器,這非常容易。讓我們建立一個新的自定義匹配器,它返回一個匹配器來測試 TextView 的 id 和文字。

Espresso 提供以下兩個類來編寫新的匹配器:

  • TypeSafeMatcher

  • BoundedMatcher

這兩個類的性質相似,除了 BoundedMatcher 透明地處理物件的型別轉換到正確的型別,而無需手動檢查正確的型別。我們將使用 BoundedMatcher 類建立一個新的匹配器 withIdAndText。讓我們檢查編寫新匹配器的步驟。

  • app/build.gradle 檔案中新增以下依賴項並同步。

dependencies {
   implementation 'androidx.test.espresso:espresso-core:3.1.1'
}
  • 建立一個新類來包含我們的匹配器(方法)並將其標記為 final

public final class MyMatchers {
}
  • 在新類中宣告一個靜態方法,並使用必要的引數,並將 Matcher<View> 設定為返回型別。

public final class MyMatchers {
   @NonNull
   public static Matcher<View> withIdAndText(final Matcher<Integer>
   integerMatcher, final Matcher<String> stringMatcher) {
   }
}
  • 在靜態方法內部建立一個新的 BoundedMatcher 物件(也作為返回值),使用以下簽名:

public final class MyMatchers {
   @NonNull
   public static Matcher<View> withIdAndText(final Matcher<Integer>
   integerMatcher, final Matcher<String> stringMatcher) {
      return new BoundedMatcher<View, TextView>(TextView.class) {
      };
   }
}
  • BoundedMatcher 物件中覆蓋 describeTomatchesSafely 方法。describeTo 只有一個型別為 Description 的引數,沒有返回值,用於提供有關匹配器的錯誤資訊。matchesSafely 只有一個型別為 TextView 的引數,返回型別為 boolean,用於匹配檢視。

程式碼的最終版本如下所示:

public final class MyMatchers {
   @NonNull
   public static Matcher<View> withIdAndText(final Matcher<Integer>
   integerMatcher, final Matcher<String> stringMatcher) {
      return new BoundedMatcher<View, TextView>(TextView.class) {
         @Override
         public void describeTo(final Description description) {
            description.appendText("error text: ");
            stringMatcher.describeTo(description);
            integerMatcher.describeTo(description);
         }
         @Override
         public boolean matchesSafely(final TextView textView) {
            return stringMatcher.matches(textView.getText().toString()) &&
            integerMatcher.matches(textView.getId());
         }
      };
   }
}
  • 最後,我們可以使用我們的新匹配器編寫測試用例,如下所示:

@Test
public void view_customMatcher_isCorrect() {
   onView(withIdAndText(is((Integer) R.id.textView_hello), is((String) "Hello World!")))
      .check(matches(withText("Hello World!")));
}
廣告

© . All rights reserved.