Android RecyclerView适配器在单元测试中返回null

6

我正在尝试使用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)

代码中有什么问题?

你能发布你的ProductListActivity代码吗? - Bartek Lipinski
1个回答

11

从这一行可以看出:

 

期望值是com.kaushik.myredmart.adapter.ProductAdapter的一个实例但实际得到的是null

可以得出结论,这个:

RecyclerView.Adapter adapter = productRecyclerView.getAdapter();

返回null,这可能是由于未执行productRecyclerView.setAdapter(adapter)。确保在活动生命周期回调中正确设置适配器(例如在onCreate()中)。我觉得你是在某个操作/回调之后创建并设置适配器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接