Espresso测试:
@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()));
}
当perfom点击时,网络请求开始。当网络响应速度快时,测试通过。行。
但是当网络响应很慢(例如10秒)或根本没有网络时,测试失败并出现错误:
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}
那么如何解决这个问题呢?使用存根网络响应(例如Mockito)?
答案 0 :(得分:1)
选择以下两种方式之一:
IdlingResource
等待回复(不是很优雅;你会让你的考试时间更长;如果没有可用的互联网,我们会帮助你)。可以找到最简单的实现here。答案 1 :(得分:0)
我建议使用像Dagger这样的依赖注入工具将测试网络从测试app-flow中分离出去。
这是一篇很好的文章: Android testing using Dagger 2, Mockito and a custom JUnit rule