Android RecyclerView适配器在单元测试时给出null

dev*_*oid 6 java android recycler-adapter android-recyclerview android-junit

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

    }
}
Run Code Online (Sandbox Code Playgroud)

我正面临检查适配器的问题.虽然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)
Run Code Online (Sandbox Code Playgroud)

代码中有什么问题?

azi*_*ian 10

从这条线来看:

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

可以得出结论,这个:

RecyclerView.Adapter adapter = productRecyclerView.getAdapter();
Run Code Online (Sandbox Code Playgroud)

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

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