Might be too late but you should take a look at espresso idling resource to sync your background loading tasks with espresso. You wont need to change any of your application code. Here you have a deeper insight on android custom idling resources: http://dev.jimdo.com/2014/05/09/wait-for-it-a-deep-dive-into-espresso-s-idling-resources/
or this http://blog.sqisland.com/2015/04/espresso-custom-idling-resource.html
Here is what I did to make espresso wait for my list to be populated (from data comming from the network) before running the UI test.
public class ListResultsIdlingResource implements IdlingResource {
private ResourceCallback callback;
private RecyclerView mRecyclerListings;
public ListResultsIdlingResource(RecyclerView recyclerListings) {
mRecyclerListings = recyclerListings;
}
@Override
public boolean isIdleNow() {
if (mRecyclerListings != null && mRecyclerListings.getAdapter().getItemCount() > 0) {
if (callback != null) {
callback.onTransitionToIdle();
}
return true;
}
return false;
}
@Override
public void registerIdleTransitionCallback(ResourceCallback callback) {
this.callback = callback;
}
@Override
public String getName() {
return "Recycler idling resource";
}
You just have to check that your list has items in you isIdleNow() method before running your UI test over its elements.
And in your espresso test class in your setup method register your idling resource and pass it a reference to your ListView or Recyclerview or any view you are using as list.
@Before
public void setUp() throws Exception {
Intent intent = createIntentForActivity();
activityRule.launchActivity(intent);
mActivity = activityRule.getActivity();
mListResultsIdlingResource = new ListingResultsIdlingResource(
(RecyclerView) mActivity.findViewById(R.id.recycler_view));
registerIdlingResources(mListResultsIdlingResource);
}
Hope this is helpful for anyone looking for this.