Search code examples
androidandroid-fragmentsandroid-viewpagerfragmentstatepageradapterandroid-espresso

Espresso with a ViewPager, FragmentStatePagerAdapter, and api calls


I have an activity MainActivity that consists of a single ViewPager with tabs to switch between the different pages (fragments). On the first page (FragmentA, onResume()), I execute an api call to fetch data and set up views for said page onResume(). This page can be considered my home page, which all actions stem from.

Should Espresso automatically wait - once I start MainActivity - for the api call made from the first page fragment to finish if I'm using AsyncTask? Or do I need to implement the IdlingResource/Sleep for this situation? I'm not sure how the threading works for FragmentStatePagerAdapters and ViewPagers.

Is this the best way to test this? Do I need to refactor code to make api calls and such from the MainActivity instead of in the fragments?


Solution

  • Turns out that I wasn't really using AsyncTask for api calls. I'm using Retrofit and had the following:

        if (ActivityManager.isRunningInTestHarness()) {
            d(TAG, "Using AsyncTask thread pool executor!");
            adapter.setExecutors(AsyncTask.THREAD_POOL_EXECUTOR, new MainThreadExecutor())
                   .build();
        } else {
            d(TAG, "Using nonAsyncTask thread pool executor!");
            adapter.setClient(new OkClient(getBaseClient()));
        }
    

    ActivityManager.isRunningInTestHarness() did not return true when executing espresso tests like I expected. Removing the if statement resolved my issue.