使用doesNotExist的Android Espresso onData

sjo*_*nes 6 android android-espresso

我试图验证a ListView不包含特定项目.这是我正在使用的代码:

onData(allOf(is(instanceOf(Contact.class)), is(withContactItemName(is("TestName")))))
      .check(doesNotExist());
Run Code Online (Sandbox Code Playgroud)

当名称存在时,我正确地得到错误,因为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")
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得这样的功能onData(...).check(doesNotExist())

编辑:

通过使用try/catch并检查事件的getCause(),我有一个可怕的黑客来获得我想要的功能.我很想用一种好的技术取而代之.

den*_*nys 13

根据Espresso样本,您不得使用onData(...)以检查适配器中是否存在视图.看看这个 - 链接.阅读"断言数据项不在适配器中"部分.你必须使用匹配器onView()找到AdapterView.

基于以上链接的Espresso样品:

  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;
            }
        };
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 那么onView(...),R.id.list适配器ListView的id 在哪里:

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

还有一个建议 - 避免编写is(withContactItemName(is("TestName"))以下代码添加到匹配器:

    public static Matcher<Object> withContactItemName(String itemText) {
        checkArgument( itemText != null );
        return withContactItemName(equalTo(itemText));
    }
Run Code Online (Sandbox Code Playgroud)

那么你将拥有更多可读和清晰的代码 is(withContactItemName("TestName")