Espresso loop over tests

Issue

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.setText(str);
        b.setId(j);

        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                Intent i  new Intent(MainActivity.this, NewActivity.class);
                i.putExtra("key",str);
                startActivity(i);
            }
        });

        gridLayout.addView(b,j);
    } 

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:

@Test
public void testOneButton() {
    onView(withId(R.id.button)).check(matches(notNullValue()));
    onView(withId(R.id.button)).check(matches(withText(R.string.button_text)));
    onView(withId(R.id.button)).perform(click());

    // in new activity
    CharSequence title  InstrumentationRegistry.getTargetContext()
            .getString(R.string.new_activity_title);
    matchToolbarTitle(title);

}

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++) {
    @Test
    testButton(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?

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

Solution

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