Android Espresso onData with doesNotExist

I am trying to verify that a ListView does not contain a specific item. Here is the code I'm using:

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

When the name exists, I get the error message correctly due to check(doesNotExist()) . When the name does not exist, I get the following error, because allOf(...) does not match anything:

 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") 

How can I get functions like onData(...).check(doesNotExist()) ?

EDIT:

I have a terrible hack to get the functionality that I would like to use using try / catch and checking the getCause () event. I would like to replace this with a good technique.

+6
source share
1 answer

According to Espresso samples, you should not use onData(...) to check if there is a view in the adapter. Check it out - link . Read the "Statement that the data item is not in the adapter." You must use the match along with onView() , which the AdapterView finds.

Based on espresso samples from the above link:

  • agreement:

     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; } }; } 
  • then onView(...) , where R.id.list is the identifier of your ListView adapter:

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

And one more suggestion - to avoid writing is(withContactItemName(is("TestName")) , add the code below to your interlocutor:

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

then you will have more readable and understandable code is(withContactItemName("TestName")

+12
source

All Articles