我正在尝试验证 ListView
不包含特定项目。这是我正在使用的代码:
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(),我获得了我想要的功能,这很糟糕。我很乐意用一种好的技术来代替它。
最佳答案
根据 Espresso 示例,您不得使用 onData(...)
来检查适配器中是否不存在 View 。检查一下 - link .阅读“断言数据项不在适配器中”部分。您必须将匹配器与找到 AdapterView 的 onView()
一起使用。
基于上面链接中的 Espresso sample :
匹配器:
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; } }; }
然后
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 != null );
return withContactItemName(equalTo(itemText));
}
那么您将拥有更易读和清晰的代码 is(withContactItemName("TestName")
关于带有 doesNotExist 的 Android Espresso onData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21173253/