Robolectric and Retrofit - wait for response
<p>I would like to test if my code is correctly downloading data from API (using Retrofit) and displays them in RecyclerView. In order to do this I created an interceptor which mocks API (basing on <a href="https://stackoverflow.com/a/34375411/1828352">this solution</a>) and created a test (using Robolectric):</p>

<pre><code>    @Test
    public void listLoadedCorrectlyTest() {
        MyListFragment myListFragment = new MyListFragment();
        Bundle args = new Bundle();
        FragmentTestUtil.startFragment(myListFragment);
        Robolectric.flushForegroundThreadScheduler();
        JSONArray responseArray = new JSONArray();
        try {
            responseArray = new JSONArray(ApiInterceptor.MOCK_RESPONSE);
        } catch (JSONException e) {
            Log.e("JSON", e.getMessage());
        }
        int adapterItemCount = ((RecyclerView) myListFragment.getView()
                .findViewById(R.id.rv_fruits)).getAdapter().getItemCount();
        assertThat(adapterItemCount).isEqualTo(responseArray.length());
    }
</code></pre>

<p>The problem is that the test is sometimes passed and sometimes failed. I've debugged the code and I know that this is because the data in <code>MyListFragment</code> are loaded to the <code>rv_fruits</code> <code>RecyclerView</code> using Retrofit's <code>enqueue()</code> method. How can I wait for the Retrofit callback so that the assertion is checked AFTER the data are loaded to the <code>RecyclerView</code>?</p>