Alexei
Alexei

Reputation: 15646

How test (Espresso) when no network or network response is slow?

Espresso test:

@Test
public void searchSwipeAddFavorite() {
onData(anything()).inAdapterView(withId(R.id.container_ListView)).atPosition(0).onChildView(withText(R.string.add_to_favorites))
            .perform(click());
onData(anything()).inAdapterView(withId(R.id.container_ListView)).atPosition(0).onChildView(withText(R.string.remove_from_favorites))
            .check(matches(isDisplayed()));
}

When perfom click the network request is start. When the network response is speed the test pass. OK.

But when network response is slow (e.g. 10 sec) or no network at all then test is fail with error:

    android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: (with string from resource id: <2131165341>[remove_from_favorites] value: Remove from favorite
 and is descendant of a:  displaying data matching: ANYTHING within adapter view matching: with id: com.my_project.android.dev:id/container_ListView)
If the target view is not part of the view hierarchy, you may need to use Espresso.onData to load it from one of the following AdapterViews:com.baoyz.swipemenulistview.SwipeMenuListView{ad24d3e0 VFED.VC. ........ 0,168-480,642 #7f0e0082 app:id/containerNotEmptyListView}

So how to fix this problem? Use stub network response (e.g. by Mockito)?

Upvotes: 0

Views: 1505

Answers (2)

Maher Abuthraa
Maher Abuthraa

Reputation: 17813

I would recommend to split testing network from testing app-flow by using dependency injections tools like Dagger.

Here is a nice article: Android testing using Dagger 2, Mockito and a custom JUnit rule

Upvotes: 0

Bartek Lipinski
Bartek Lipinski

Reputation: 31438

Choose one of two ways:

  1. Mock your responses (e.g. using Mockito). The exact implementation depends on your code.
  2. Introduce IdlingResource to wait for the response (not really elegant; you will make your tests longer; won't help you if there's no internet available). The simplest implementation can be found here.

Upvotes: 1

Related Questions