2014-01-16 30 views
6

我在嘗試驗證ListView不包含特定項目。下面是我使用的代碼:Android Espresso onData with doesNotExist

onData(allOf(is(instanceOf(Contact.class)), is(withContactItemName(is("TestName"))))) 
     .check(doesNotExist()); 

當名存在,我得到正確,因爲check(doesNotExist())錯誤。如果名稱不存在,我得到以下錯誤,因爲allOf(...)不匹配任何東西:

Caused by: java.lang.RuntimeException: No data found matching: 
(is an instance of layer.sdk.contacts.Contact and is with contact item name: 
is "TestName") 

我怎樣才能像onData(...).check(doesNotExist())功能?

編輯:

我有一個可怕的黑客拿到我用的try/catch和檢查活動的的getCause喜歡()的功能。我很樂意用一種很好的技術來取代它。

回答

12

根據Espresso樣本,您不能使用onData(...)來檢查適配器中是否存在視圖。檢查一下 - link。閱讀「聲明數據項不在適配器中」部分。你必須使用一個匹配器和onView()來找到AdapterView。

基於從鏈接咖啡樣品上面:

  1. 匹配:

    private static Matcher<View> withAdaptedData(final Matcher<Object> dataMatcher) { 
        return new TypeSafeMatcher<View>() { 
    
         @Override 
         public void describeTo(Description description) { 
          description.appendText("with class name: "); 
          dataMatcher.describeTo(description); 
         } 
    
         @Override 
         public boolean matchesSafely(View view) { 
          if (!(view instanceof AdapterView)) { 
           return false; 
          } 
    
          @SuppressWarnings("rawtypes") 
          Adapter adapter = ((AdapterView) view).getAdapter(); 
          for (int i = 0; i < adapter.getCount(); i++) { 
           if (dataMatcher.matches(adapter.getItem(i))) { 
            return true; 
           } 
          } 
          return false; 
         } 
        }; 
    } 
    
  2. 然後onView(...),其中R.id.list是您的適配器的ListView的ID:

    @SuppressWarnings("unchecked") 
    public void testDataItemNotInAdapter(){ 
        onView(withId(R.id.list)) 
         .check(matches(not(withAdaptedData(is(withContactItemName("TestName")))))); 
    } 
    

還有一項建議 - 避免編寫is(withContactItemName(is("TestName"))下面的代碼添加到您的匹配:

public static Matcher<Object> withContactItemName(String itemText) { 
     checkArgument(!(itemText.equals(null))); 
     return withContactItemName(equalTo(itemText)); 
    } 

,那麼你將有更多的可讀性和清晰的代碼is(withContactItemName("TestName")

+3

的文檔移動到這裏:https://開頭谷歌.github.io/Android的測試支持庫/文檔/咖啡/高級/#斷言,即,一個數據項 - 是 - 不在位的適配器 – friedger