Krishnakant
Krishnakant

Reputation: 1523

Assert EditText Value in Espresso

Can we perform assertion on Edittext Value and write down our test case according to it's output. Like if we Edittext value is Equal to our value we want to perform Condition A else B.

 onView(withId(viewId)).check(matches(isEditTextValueEqualTo(viewId, value)));

Matcher<View> isEditTextValueEqualTo(final int viewId, final String content) {

    return new TypeSafeMatcher<View>() {

        @Override
        public void describeTo(Description description) {
            description.appendText("Match Edit Text Value with View ID Value : :  " + content);
        }

        @Override
        public boolean matchesSafely(View view) {
            if (view != null) {
                String editTextValue = ((EditText) view.findViewById(viewId)).getText().toString();

                if (editTextValue.equalsIgnoreCase(content)) {
                    return true;
                }
            }
            return false;
        }
    };
}

This is not working using try.. Catch(Exception e)

Upvotes: 3

Views: 3015

Answers (2)

Krishnakant
Krishnakant

Reputation: 1523

When I check the value and assertion failed it throws AssertionFailedError which is not in hierarchy of Exception. It gets fixed with try... catch(AssertionFailedError e)

Upvotes: 0

jeprubio
jeprubio

Reputation: 18022

I don't think you shoud do a findViewById inside the matcher, I see no reason to do this.

I have updated your matcher:

Matcher<View> isEditTextValueEqualTo(final String content) {

    return new TypeSafeMatcher<View>() {

        @Override
        public void describeTo(Description description) {
            description.appendText("Match Edit Text Value with View ID Value : :  " + content);
        }

        @Override
        public boolean matchesSafely(View view) {
            if (!(view instanceof TextView) && !(view instanceof EditText)) {
                    return false;
            }
            if (view != null) {
                String text;
                if (view instanceof TextView) {
                    text =((TextView) view).getText().toString();
                } else {
                    text =((EditText) view).getText().toString();
                }

                return (text.equalsIgnoreCase(content));
            }
            return false;
        }
    };
}

And call it this way:

onView(withId(viewId)).check(matches(isEditTextValueEqualTo(value)));

Upvotes: 4

Related Questions