【发布时间】:2016-08-02 02:19:23
【问题描述】:
我想测试我的代码是否正确地从 API 下载数据(使用 Retrofit)并将它们显示在 RecyclerView 中。为此,我创建了一个模拟 API 的拦截器(基于 this solution)并创建了一个测试(使用 Robolectric):
@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());
}
问题是测试有时通过,有时失败。我已经调试了代码,我知道这是因为 MyListFragment 中的数据是使用 Retrofit 的 enqueue() 方法加载到 rv_fruits RecyclerView 的。如何等待 Retrofit 回调,以便在将数据加载到 RecyclerView 后检查断言?
【问题讨论】:
-
你能显示你的片段代码吗?你可以在那里模拟网络吗?
标签: android retrofit robolectric android-testing retrofit2