Espresso loop over tests


I have an activity with a GridView of buttons which I create programmatically in a for loop taking text from a string array.

for(int j0; j < string_array.length; j++) {
        final String str  string_array[j];
        Button b new Button(getApplicationContext());

        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                Intent i  new Intent(MainActivity.this, NewActivity.class);


Using Espresso I would like to test whether buttons exist, have proper text and whether clicking on a button takes me to another activity (check title text).

For one button I have the following test which works:

public void testOneButton() {

    // in new activity
    CharSequence title  InstrumentationRegistry.getTargetContext()


How can I write tests for all the buttons in the GridView not fixing the string_array? After “perform(click())”, I am in a new activity so cannot perform another click on a button in the old/original activity. Is it possible to write something like,

for(int j0; j < string_array.length; j++) {

where “testButton(j)” is basically the same test as testOneButton, parametrized for the respective buttons with id “j”?

Or is it possible in Espresso to return to the original activity and have a structure like?

public void testButtons() {
    for (int j0; j<string.array.length; j++) {
        // test button with id "j"
        // return to original activity


I used the second version for what I needed to do into my app. You can use Espresso method pressBack() to go back to the main activity. Hope this helps. Good luck!

Answered By – sunlover3

Leave a Comment