我想测试 EditText 字段是否有错误(使用 editText.setError("Cannot be blank!") 设置)。
我使用新的 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/