Android Espresso not waiting for UI to finish
<p>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.</p>

<p>The dialog is defined like this:</p>

<pre><code>&lt;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" /&gt;
</code></pre>

<p>Espresso opens it like this:</p>

<pre><code>onView(withText(mActivityRule.getActivity().getResources().getString(R.string.pref_title_VALUE))
    .perform(click());
</code></pre>

<p>This does open the ListPreference, but it doesn't block and the next line in the test runs immediately. </p>

<pre><code>// click on setting
    onView(withText(VALUE_IN_LIST_PREFERENCE))
            .perform(click());
</code></pre>

<p>Since that happens immediately, the dialog has not appeared and withText(VALUE_IN_LIST_PREFERENCE) matches nothing.</p>

<p>If I step through with a debugger, pausing on the line above, the dialog will appear in time and the code will work.</p>

<p>The same problem then happens with the nav drawer. It's opened like this:</p>

<pre><code>// open the nav drawer
    onView(withId(R.id.drawer_layout))
            .perform(DrawerActions.open());
</code></pre>

<p>And an item is clicked on:</p>

<pre><code>// click on phase 1
    onView(withId(R.id.nav_view))
            .perform(NavigationViewActions.navigateTo(R.id.nav_ITEM));
</code></pre>

<p>As with the ListPreferences, the test code continues without waiting for the UI to finish and so the call to onView fails.</p>

<p>I have tried putting the Thread to sleep and following the answer here <a href="https://stackoverflow.com/a/22563297/4950621">https://stackoverflow.com/a/22563297/4950621</a></p>

<p>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.</p>

<p>How do I ensure that the Espresso tests are not run until the necessary Views are visible?</p>