2016-08-29 5 views
8

Ich möchte testen, ob ein EditText-Feld einen Fehler hat (festgelegt mit editText.setError ("Kann nicht leer sein!")).Testing EditText Fehler mit Espresso auf Android

EditText field with error

Ich habe einen Espresso Testfall mit dem neuen Android Studio 2.2 Feature erstellt, um Espresso Tests aufzuzeichnen. Also ist der Code ziemlich automatisch generiert. Aber vorerst überprüft es nur, ob der editText angezeigt wird.

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

Gibt es eine Möglichkeit zu testen, ob der Fehler angezeigt wird?

+0

versuchen adnotation @Nullable – Genehme

+0

Mögliche Duplikat [Android Espresso hinzufügen. Wie man ErrorText in TextInputLayout prüft] (http://stackoverflow.com/questions/34285782/android-espresso-how-to-check-errortext-in-textinputlayout) –

Antwort

17

Sie ändern editText.check(matches(isDisplayed()));-editText.check(matches(hasErrorText("Cannot be blank!")));

+0

Ya thats es! :) Vielen Dank. Ich habe nur das [Cheat Sheet] überprüft (https://google.github.io/android-testing-support-library/docs/espresso/cheatsheet/), aber es fehlen einige Methoden. –

Verwandte Themen