2

In my android app, I have a ListView of custom items (made of a clickable title + one checkbox without text). Those items are dynamically added.

How can I check one of those checkboxes in my unit tests using Espresso or a similar framework ?

I can't find how to get a reference to one of the checkboxes. Since they are dynamically added, I can't find them by id, like I usually do with static .xml views.

Julien__
  • 1,864
  • 1
  • 10
  • 22

2 Answers2

1

You need to set id for the checkboxes programatically (see this answer and this).

    int checkBoxId = 200000; // global variable to count checkboxes
    for (int i = 0; i < 1000; ++i) {
        CheckBox box = new CheckBox(this);
        box.setId(++checkBoxId);
    }

then find them as usual:

onView(withId(200003)).perform(click());
Community
  • 1
  • 1
Artem Mostyaev
  • 3,589
  • 10
  • 48
  • 55
  • Won't the ids collide with the ids in my `.xml` ? For instance the one for a `EditText` ? – Julien__ Nov 28 '16 at 21:29
  • 1
    They can in theory. I looked into my app's R.java - all ids start with `0x7f` (`0x7f010176`). So your ids shouldn't collide if they are less then `0x7f000000` – Artem Mostyaev Nov 29 '16 at 06:12
0

Here is how we did it without changing the app's code:

int indexOfItem = 1;
onData(anything()).inAdapterView(withId(R.id.listView))
            .atPosition(indexOfItem)
            .onChildView(withId(R.id.checkBox))
            .perform(click());
Julien__
  • 1,864
  • 1
  • 10
  • 22