android - 在 Android 上使用 Espresso 测试 EditText 错误

标签 android testing junit4 android-espresso

我想测试 EditText 字段是否有错误(使用 editText.setError("Cannot be blank!") 设置)。

EditText field with error

我使用新的 AndroidStudio 2.2 功能创建了一个 Espresso 测试用例,以记录 Espresso 测试。所以代码几乎是自动生成的。但现在它只检查是否显示了 editText。

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

有没有办法测试是否显示错误?

最佳答案

您将 editText.check(matches(isDisplayed())); 更改为 editText.check(matches(hasErrorText("Cannot be blank!")));

关于android - 在 Android 上使用 Espresso 测试 EditText 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39206599/

相关文章:

java - 在 java 11 http 客户端上运行 powermock + mockito

java - 如何理解 Android Studio 中的 Kotlin 文档语法

android - 如何知道 Android 操作栏的操作图标是在顶部栏还是底部栏(拆分)?

testing - Polymer 3.0 a11ySuite 测试报错

在 Python/Flask 中测试计划任务

java - 对 ArrayList 的 ArrayList 进行 Junit 测试

junit - 我们是否有任何经验法则来估算 JUnit 测试用例的工时

java - 正则表达式 YouTube IFRAME

java - 使用 LibGDX 中的触摸板仅以 45° 的步长移动播放器

php - 来自测试方法正在使用的同一类的模拟方法