Dmitriy Dmitriy - 1 year ago 52
Android Question

How to assert that a data item is not in a ListFragment with Espresso?

I have an activity with ListFragment.
I need to implement the scenario (with help of Espresso):

  1. Add new item in ListFragment.

  2. Check it is displaying.

  3. Delete this item.

  4. Check it is not displaying.

I have the issue with the fourth point.
I've read the article [][1].

Author recomends to implement the matcher:

private static Matcher<View> withAdaptedData(final Matcher<Object> dataMatcher) {
return new TypeSafeMatcher<View>() {
public void describeTo(Description description) {
description.appendText("with class name: ");

public boolean matchesSafely(View view) {
if (!(view instanceof AdapterView)) {
return false;
Adapter adapter = ((AdapterView) view).getAdapter();
for (int i = 0; i < adapter.getCount(); i++) {
if (dataMatcher.matches(adapter.getItem(i))) {
return true;
return false;

And then calls:

.check(matches(not(withAdaptedData(withItemContent("item: 168")))));

The problem is that in my case I do not have AdapterView. I pass id of ListFragment in function withId(). So the matcher does not work.
The question is how to change the code of withAdaptedData to it works with ListFragment? Or, may be, there are another way to solve my task?

Answer Source

Unfortunately, I didn't find out anything better than do not use Espresso to solve this problem. I just implement the method to check that data is not in ListFragment.

    private void checkDataNotExistInList(String text) {
        MyListFragment myListFragment = (MyListFragment)mActivity.getFragmentManager()
        if (myListFragment != null) {
            ListAdapter listAdapter = (ListAdapter) myListFragment.getListAdapter();
            for (int i = 0; i < listAdapter.getCount(); i++) {
                assertThat("Item is in the list", text, is(not(listAdapter.getItem(i).getName())));

But I belive there is the better solution.