有人可以告诉我为什么这不起作用
onView(withId(R.id.edt_apikey)).check(matches(hasErrorText(anyString())));
在logcat中显示:
android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with error: is ""' doesn't match the selected view.
Expected: with error: is ""
Got: "AppCompatEditText{id=2131492985, res-name=edt_apikey, visibility=VISIBLE, width=517, height=83, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=true, editor-info=[inputType=0x80001 imeOptions=0xc000005 privateImeOptions=null actionLabel=null actionId=0 initialSelStart=0 initialSelEnd=0 initialCapsMode=0x0 hintText=1c915e3b5d42d05136185030892fbb846c278927 label=null packageName=null fieldId=0 fieldName=null extras=null ], x=139.0, y=83.0, text=, error-text=This field is required, hint=1c915e3b5d42d05136185030892fbb846c278927, input-type=524289, ime-target=false, has-links=false}"
我猜上面的内容不起作用,因为它是一个Mockito匹配器。 所以我尝试了这个:
import static android.support.test.espresso.matcher.ViewMatchers.hasErrorText;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
onView(withId(R.id.edt_apikey)).check(matches(hasErrorText(not(isEmptyOrNullString()))));
它也不起作用。给出这个例外...
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference
at android.support.test.espresso.matcher.ViewMatchers$34.matchesSafely(ViewMatchers.java:1130)
at android.support.test.espresso.matcher.ViewMatchers$34.matchesSafely(ViewMatchers.java:1120)
答案 0 :(得分:2)
临时解决方案是创建自定义匹配器
public static Matcher<View> hasErrorText(final Matcher<String> stringMatcher) {
checkNotNull(stringMatcher);
return new BoundedMatcher<View, EditText>(EditText.class) {
@Override
public void describeTo(Description description) {
description.appendText("with error: ");
stringMatcher.describeTo(description);
}
@Override
protected boolean matchesSafely(EditText view) {
if (view.getError() == null) return stringMatcher.matches(view.getError());
return stringMatcher.matches(view.getError().toString());
}
};
}
然后使用它
onView(withId(R.id.edt_apikey)).check(matches(hasErrorText(not(Matchers.isEmptyOrNullString()))));
答案 1 :(得分:0)
看来你的测试代码:
onView(withId(R.id.edt_apikey)).check(matches(hasErrorText(anyString())));
返回null
个对象。我还没有使用anything()
Hamcrest匹配器,但是如果你真的想检查错误信息是否为空,那么好的选择可能是这样的代码:
onView(withId(R.id.edt_apikey)).check(matches(withText("")));
希望有所帮助