Android RecyclerView Adapter 在单元测试中给出 null

Android RecyclerView Adapter is giving null on unit testing

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

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 的实例,但它在最后一行出现以下错误:

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)

代码中有什么问题?

从这一行判断:

Expected: an instance of com.kaushik.myredmart.adapter.ProductAdapter but: null

可以得出这样的结论:

RecyclerView.Adapter adapter = productRecyclerView.getAdapter();

returnsnull,没有执行的时候可能会出现productRecyclerView.setAdapter(adapter).

确保您在 activity 生命周期回调中(即在 onCreate() 中)正确设置了适配器。在我看来,您是在 action/callback.

之后创建和设置适配器的