DeBuGGeR DeBuGGeR - 1 year ago 144
Java Question

Using espresso view matcher with hamcrest matchers

Can someone please tell me why does not this works


Shows this in logcat:$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}"

I guess the above doesn't work since it was a Mockito matcher.
So I tried this:

import static;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;


And it doesn't works either. Giving this exception...

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference

Answer Source

The temporary solution is to create a custom matcher

public static Matcher<View> hasErrorText(final Matcher<String> stringMatcher) {
    return new BoundedMatcher<View, EditText>(EditText.class) {

        public void describeTo(Description description) {
            description.appendText("with error: ");

        protected boolean matchesSafely(EditText view) {
            if (view.getError() == null) return stringMatcher.matches(view.getError());
            return stringMatcher.matches(view.getError().toString());

And then use it like onView(withId(;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download