在 Espresso 中断言 EditText 值

Assert EditText Value in Espresso

我们可以对 Edittext Value 执行断言并根据它的输出写下我们的测试用例吗?就像我们的 Edittext 值等于我们想要执行条件 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;
        }
    };
}

使用 try..Catch(Exception e) 无效

我认为您不应该在匹配器中执行 findViewById,我认为没有理由这样做。

我已经更新了你的匹配器:

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;
        }
    };
}

并这样称呼它:

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

当我检查值并且断言失败时,它抛出不在异常层次结构中的 AssertionFailedError。它通过 try...catch(AssertionFailedError e)

修复