在Android上使用EspressotestingEditText错误

我想testing一个EditText字段是否有错误(使用editText.setError(“Can not be blank!”))。

有错误的EditText字段

我用新的AndroidStudio 2.2function创build了一个Espressotesting用例来loggingEspressotesting。 所以代码几乎是自动生成的。 但现在它只检查是否显示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)); } }; } } 

有没有办法testing错误是否显示?

你改变editText.check(matches(isDisplayed())); editText.check(matches(hasErrorText("Cannot be blank!")));