2016-08-29 55 views
8

我想測試EditText字段是否有錯誤(使用editText.setError(「Can not be blank!」)設置)。使用Android上的Espresso測試EditText錯誤

EditText field with error

我創建了一個咖啡測試用例與新AndroidStudio 2.2功能,記錄咖啡的測試。所以代碼幾乎是自動生成的。但現在它只檢查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)); 
      } 
     }; 
    } 
} 

有沒有方法可以測試錯誤是否顯示?

+0

嘗試添加adnotation [安卓咖啡的 @Nullable – Genehme

+0

可能的複製。如何檢查TextInputLayout中的ErrorText](http://stackoverflow.com/questions/34285782/android-espresso-how-to-check-errortext-in-textinputlayout) –

回答

17

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

+0

遐哉! :) 謝謝。我只檢查了[備忘單](https://google.github.io/android-testing-support-library/docs/espresso/cheatsheet/),但缺少一些方法。 –

相關問題