android - 如何通过 Espresso android.widget.TextView setError 进行测试?

标签 android testing textview android-espresso

我有 password.setError(getResources().getString(R.string.incorrect_data)); 如果我设置了无效密码 - 显示带有文本“无效数据!”的 textView, 我需要用 Espresso 测试它,我写道:

onView(withText(R.string.incorrect_data)).check(matches(isDisplayed()));

但是错了,我有:

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with string from resource id: <2131493034>[incorrect_data] value: Invalid data!
If the target view is not part of the view hierarchy, you may need to use Espresso.onData to load it from one of the following AdapterViews:android.widget.ListView{307b4f3a IFED.VC. ......ID -480,0-0,1022 #7f0a004c app:id/left_drawer}

如果我写:onView(withText("Invalid data!")).check(matches(isDisplayed()));

我有:

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with text: is "Invalid data!"
If the target view is not part of the view hierarchy, you may need to use Espresso.onData to load it from one of the following AdapterViews:android.widget.ListView{307b4f3a IFED.VC. ......ID -480,0-0,1022 #7f0a004c app:id/left_drawer}

我使用 Espresso 2:

import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static android.support.test.espresso.Espresso.onView;

请帮帮我

最佳答案

帮助我:

onView(withId(R.id.password)).check(matches(withError(
                getActivity().getString(R.string.incorrect_data))));

private static Matcher<View> withError(final String expected) {
        return new TypeSafeMatcher<View>() {

            @Override
            public boolean matchesSafely(View view) {
                if (!(view instanceof EditText)) {
                    return false;
                }
                EditText editText = (EditText) view;
                return editText.getError().toString().equals(expected);
            }

            @Override
            public void describeTo(Description description) {

            }
        };
    }

关于android - 如何通过 Espresso android.widget.TextView setError 进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28408114/

相关文章:

testing - EasyMock - 如何重置模拟但保持预期?

android - 自定义字体 TextView 的性能问题

android - 为什么它告诉我在我使用 android :text ="' ? 的任何地方使用 @string/而且它是硬编码的

android - Android 上的 pcsc-lite 和 ccid

android - 将列表的行 ID 传递给另一个 Activity

android - 简单的 TextView.setText 导致 40% 的 CPU 使用率

angular - 测试方法 setter @Input() Angular 4 Karma

javascript - 在对象数组上使用 Jest 属性匹配器

java - EditText 输入金额

android - 将 Android 应用程序 list 文件分成几个部分