Android RecyclerView适配器在unit testing时给出null

我正在尝试使用AndroidJunit4测试RecyclerView,这是我的测试代码:

package com.kaushik.myredmart.ui; // all includes @RunWith(AndroidJUnit4.class) public class ProductListActivityTest { @Rule public ActivityTestRule 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传递非null测试和RecyclerView的实例,但它在最后一行中跟随错误:

 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

可以得出结论,这个:

 RecyclerView.Adapter adapter = productRecyclerView.getAdapter(); 

返回null ,这可能在没有执行productRecyclerView.setAdapter(adapter)

确保在活动生命周期回调中正确设置适配器(即在onCreate() )。 在我看来,你是在一些动作/回调后创建和设置适配器。

正如@azizbekian所提到的,你应该在onCreate()的activity中设置适配器。