Android RecyclerView适配器在单元测试时给出null [英] Android RecyclerView Adapter is giving null on unit testing
问题描述
我正在尝试使用AndroidJunit4测试RecyclerView,这是我的测试代码:
I am trying to test RecyclerView with AndroidJunit4, it is my test code:
package com.kaushik.myredmart.ui;
// all includes
@RunWith(AndroidJUnit4.class)
public class ProductListActivityTest {
@Rule
public ActivityTestRule<ProductListActivity> rule = new ActivityTestRule<>(ProductListActivity.class);
@Test
public void ensureListViewIsPresent() throws Exception {
ProductListActivity activity = rule.getActivity();
View viewByIdw = activity.findViewById(R.id.productListView);
assertThat(viewByIdw,notNullValue());
assertThat(viewByIdw, instanceOf(RecyclerView.class));
RecyclerView productRecyclerView = (RecyclerView) viewByIdw;
RecyclerView.Adapter adapter = productRecyclerView.getAdapter();
assertThat(adapter, instanceOf(ProductAdapter.class));
}
}
我正面临检查问题适配器。虽然productRecyclerView传递非空测试和RecyclerView实例,但它在最后一行中跟随错误:
I am facing a problem to check the Adapter. Although productRecyclerView is passing not null test and an instance of RecyclerView, it is following error in last line:
java.lang.AssertionError:
Expected: an instance of com.kaushik.myredmart.adapter.ProductAdapter
but: null
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.junit.Assert.assertThat(Assert.java:956)
at org.junit.Assert.assertThat(Assert.java:923)
at com.kaushik.myredmart.ui.ProductListActivityTest.ensureListViewIsPresent(ProductListActivityTest.java:45)
代码中有什么问题?
推荐答案
从这一行判断:
预期:com的一个实例.kaushik.myredmart.adapter.ProductAdapter
但是:null
Expected: an instance of com.kaushik.myredmart.adapter.ProductAdapter but: null
可以得出结论:
RecyclerView.Adapter adapter = productRecyclerView.getAdapter();
返回 null
,这可能发生在那里尚未执行 productRecyclerView.setAdapter(适配器)
。
returns null
, which may happen when there has not been performed productRecyclerView.setAdapter(adapter)
.
确保在活动生命周期回调中正确设置适配器(即在 onCreate()
)。在我看来,你是在一些动作/回调后创建和设置适配器。
Make sure you are correctly setting adapter in activity lifecycle callbacks (i.e. in onCreate()
). It seems to me you are creating and setting adapter after some action/callback.
这篇关于Android RecyclerView适配器在单元测试时给出null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!