Espresso 中 ViewAssertion 的说明

Descriptions for ViewAssertion in Espresso

我有这个代码:

onView(withId(R.id.my_view)).check(matches(isDisplayed()))

如果测试失败并出现错误,我如何向其中添加自己的消息? 例如在 junit 中:

assertEquals("My message", expected, actual)

您可以创建自己的自定义方法,例如 isVisible(int id),其实现如下所示:

public boolean isVisible(int elementId) {
 try {
  onView(withId(R.id.elementId)).check(matches(isDisplayed()));
  return true;
} catch(Throwable t) {
   return false;
}
}

你在测试中的断言看起来像这样:

assertEquals("My failure message", expected, isVisible(R.id.someID));

您可以编写自己的自定义匹配器。以下代码将检查 EditText 中的提示。查看 this 示例:

private Matcher<View> withHint(final Matcher<String> stringMatcher) {
    checkNotNull(stringMatcher);
    return new BoundedMatcher<View, EditText>(EditText.class) {

        @Override
        public boolean matchesSafely(EditText view) {
            final CharSequence hint = view.getHint();
            return hint != null && stringMatcher.matches(hint.toString());
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("YOUR WHATEVER CUSTOM MESSAGE");
            stringMatcher.describeTo(description);
        }
    };

}

另一种选择是使用 Espresso .withFailureHandler() 并编写一个通用的失败处理程序,使用 fail(String; 方法使测试失败。

这里有更多这个故障处理程序: https://developer.android.com/reference/android/support/test/espresso/ViewInteraction.html#withFailureHandler(android.support.test.espresso.FailureHandler)