用於測試 TextView 錯誤訊息的自定義匹配器的示例

  1. 使用以下程式碼在測試包中建立類名 ErrorMatcher
public class ErrorMatcher {

    @NonNull
    public static Matcher<View> withError(final String expectedErrorText) {
        Checks.checkNotNull(expectedErrorText);
        return new BoundedMatcher<View, TextView>(TextView.class) {    
            @Override
            public void describeTo(final Description description) {
                description.appendText("error text: ");
                stringMatcher.describeTo(description);
            }
                
            @Override
            public boolean matchesSafely(final TextView textView) {
                return expectedErrorText.equals(textView.getError().toString());
            }
        };
    }
}

匹配邏輯是找到 TextView 元素,該錯誤訊息文字等於預期的錯誤文字值,通過佈局層次結構中存在的 TextView 欄位的子集。describeTo 方法用於除錯輸出。

  1. 然後,你可以在測試用例中使用自定義匹配器,如下所示:
@Test  
public void verifiesSignInErrorIsShown() {
    onView(withId(R.id.email_sign_in_button)).perform(click());
    onView(ErrorMatcher.withError("Your error text")).check(matches(isDisplayed()));
}