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)

代码中的问题是什么?

4

1 回答 1

11

从这一行来看:

预期:com.kaushik.myredmart.adapter.ProductAdapter 的一个实例,但:null

可以得出这样的结论:

RecyclerView.Adapter adapter = productRecyclerView.getAdapter();

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

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

于 2017-05-04T15:01:13.667 回答