Test if an EditText view has no error text set with Espresso on Android?

Issue

I know how to test if an error text is set in an EditText:

editText.check(matches(hasErrorText("")));

Now I want to test if an EditText has no error text set. I’ve tried this, but it does not work.

editText.check((matches(not(hasErrorText("")))));

Does anyone know how to do that? Thanks!

Solution

I don’t think it’s possible that way, depending on what you want exactly, I would use a custom matcher:

public static Matcher<View> hasNoErrorText() {
    return new BoundedMatcher<View, EditText>(EditText.class) {

        @Override
        public void describeTo(Description description) {
            description.appendText("has no error text: ");
        }

        @Override
        protected boolean matchesSafely(EditText view) {
            return view.getError()  null;
        }
    };
}

This matcher can check if an EditText does not have any error text set, use it like this:

onView(allOf(withId(R.id.edittext), isDisplayed())).check(matches(hasNoErrorText()));

Answered By – stamanuel

Leave a Comment