我有这段代码:
onView(withId(R.id.my_view)).check(matches(isDisplayed()))
如果测试失败,如何在错误的情况下添加自己的消息? 例如,如junit:
assertEquals("My message", expected, actual)
答案 0 :(得分:0)
您可以创建自己的自定义方法,如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));
答案 1 :(得分:0)
您可以编写自己的自定义匹配器。以下代码将检查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);
}
};
}
答案 2 :(得分:0)
另一种选择是使用Espresso .withFailureHandler()并编写一个通用的失败处理程序,该失败处理程序将使用fail(String; Method)使测试失败。