Michael Woywod
Michael Woywod

Reputation: 458

Testing EditText errors with Espresso on Android

I want to test if an EditText field has an error (set with editText.setError("Cannot be blank!")).

EditText field with error

I've created an Espresso test case with the new AndroidStudio 2.2 feature, to record Espresso tests. So the code is pretty much auto-generated. But for now it only checks if the editText is displayed.

@RunWith(AndroidJUnit4.class)
public class CreateNoteActivityTitleCannotBeBlank {

    @Rule
    public ActivityTestRule<CreateNoteActivity> mActivityTestRule = new ActivityTestRule<>(CreateNoteActivity.class);

    @Test
    public void createNoteActivityTitleCannotBeBlank() {
        ViewInteraction floatingActionButton = onView(
                allOf(withId(R.id.fab_add_note),
                        withParent(allOf(withId(R.id.activity_create_note),
                                withParent(withId(android.R.id.content)))),
                        isDisplayed()));
        floatingActionButton.perform(click());

        ViewInteraction editText = onView(
                allOf(withId(R.id.tiet_note_title),
                        childAtPosition(
                                childAtPosition(
                                        withId(R.id.til_title),
                                        0),
                                0),
                        isDisplayed()));
        editText.check(matches(isDisplayed()));

    }

    private static Matcher<View> childAtPosition(
            final Matcher<View> parentMatcher, final int position) {

        return new TypeSafeMatcher<View>() {
            @Override
            public void describeTo(Description description) {
                description.appendText("Child at position " + position + " in parent ");
                parentMatcher.describeTo(description);
            }

            @Override
            public boolean matchesSafely(View view) {
                ViewParent parent = view.getParent();
                return parent instanceof ViewGroup && parentMatcher.matches(parent)
                        && view.equals(((ViewGroup) parent).getChildAt(position));
            }
        };
    }
}

Is there a way to test if the error is displayed?

Upvotes: 17

Views: 9841

Answers (2)

Sajid Zeb
Sajid Zeb

Reputation: 1978

This worked for me under

        onView(withId(R.id.signin_email)).check(matches(hasErrorText("Email not valid")));

Upvotes: 2

ugurcmk
ugurcmk

Reputation: 702

You change editText.check(matches(isDisplayed())); to editText.check(matches(hasErrorText("Cannot be blank!")));

Upvotes: 36

Related Questions