【问题标题】:Android RecyclerView Adapter is giving null on unit testingAndroid RecyclerView Adapter 在单元测试中给出 null
【发布时间】:2017-09-29 13:32:12
【问题描述】:

我正在尝试使用 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代码吗?

标签: java android android-recyclerview android-junit


【解决方案1】:

从这一行来看:

预期:com.kaushik.myredmart.adapter.ProductAdapter 的实例 但是:空

可以得出这样的结论:

RecyclerView.Adapter adapter = productRecyclerView.getAdapter();

返回null,可能在没有执行productRecyclerView.setAdapter(adapter)的情况下发生。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多