Espresso onData perform click on multiple items

Issue

I have a Gridview with an adapter based on a list of pojos of type Tile for my MineSweeper game, Im doing some unit tests and all I want to do is Click on all gridview Items that dont have mines and longclick all items that does have items

I have tried with the following:

onData(allOf(is(instanceOf(Tile.class)),isMineMatcher(true)))
            .inAdapterView(withId(R.id.f_minefield_gridview))
            .perform(longClick());

onData(allOf(is(instanceOf(Tile.class)),isMineMatcher(false)))
            .inAdapterView(withId(R.id.f_minefield_gridview))
            .perform(click());

with my custom matcher:

public static Matcher<Tile> isMineMatcher(final boolean flag){
    return new TypeSafeMatcher<Tile>() {
        @Override
        public boolean matchesSafely(Tile tile) {
            return tile.isMine()  flag;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("expected "+ flag);
        }
    };
}

But this presents the following error:

android.support.test.espresso.PerformException: Error performing 'load adapter data' on view 'with id: com.kaissersoft.minesweepergame:id/f_minefield_gridview'.
...
Caused by: java.lang.RuntimeException: Multiple data elements matched:

The question is how to perform Actions on Multiple items with espresso?

Solution

Why don’t you try as it is given in testDroid. It worked for me:

If you have other objects in your adapter:

public class Person {
   public long id;
   public String firstName;
   public String lastName;
   public String email;
}

You can use this with onData :

onData(allOf(is(new BoundedMatcher<Object, Person>(Person.class) {
    @Override
    public void describeTo(Description description) {
    }
    @Override
    protected boolean matchesSafely(Person obj) {
        return obj.id  12345L;
    }
}))).inAdapterView(withId(<ADAPTER_ID>)).perform(click());

So now Person with id12345 will be found in the adapter (during test execution) and it will be clicked.

Answered By – Dinesh

Leave a Comment