I have a test that needs to open a android.support.v7.preference.ListPreference dialog, select an option, open the NavDrawer and select an item from the drawer.
The dialog is defined like this:
<android.support.v7.preference.ListPreference
android:defaultValue="@string/pref_default_VALUE"
android:entries="@array/pref_VALUE_entries"
android:entryValues="@array/pref_VALUE_values"
android:key="@string/pref_key_VALUE"
android:negativeButtonText="@null"
android:positiveButtonText="@null"
android:title="@string/pref_title_VALUE" />
Espresso opens it like this:
onView(withText(mActivityRule.getActivity().getResources().getString(R.string.pref_title_VALUE))
.perform(click());
This does open the ListPreference, but it doesn't block and the next line in the test runs immediately.
// click on setting
onView(withText(VALUE_IN_LIST_PREFERENCE))
.perform(click());
Since that happens immediately, the dialog has not appeared and withText(VALUE_IN_LIST_PREFERENCE) matches nothing.
If I step through with a debugger, pausing on the line above, the dialog will appear in time and the code will work.
The same problem then happens with the nav drawer. It's opened like this:
// open the nav drawer
onView(withId(R.id.drawer_layout))
.perform(DrawerActions.open());
And an item is clicked on:
// click on phase 1
onView(withId(R.id.nav_view))
.perform(NavigationViewActions.navigateTo(R.id.nav_ITEM));
As with the ListPreferences, the test code continues without waiting for the UI to finish and so the call to onView fails.
I have tried putting the Thread to sleep and following the answer here https://stackoverflow.com/a/22563297/4950621
In both cases, however the dialog doesn't appear until the Thread is done sleeping and the view test runs immediately. So, the problem is merely delayed, not solved.
How do I ensure that the Espresso tests are not run until the necessary Views are visible?