Android RecyclerView Adapter is giving null on unit testing

[亡魂溺海] 提交于 2019-12-07 03:09:02

问题


I am trying to test RecyclerView with AndroidJunit4, it is my test code:

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));

    }
}

I am facing a problem to check the Adapter. Although productRecyclerView is passing not null test and an instance of RecyclerView, it is following error in last line:

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)

What is the problem in code?


回答1:


Judging from this line:

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

One can conclude, that this:

RecyclerView.Adapter adapter = productRecyclerView.getAdapter();

returns null, which may happen when there has not been performed productRecyclerView.setAdapter(adapter).

Make sure you are correctly setting adapter in activity lifecycle callbacks (i.e. in onCreate()). It seems to me you are creating and setting adapter after some action/callback.



来源:https://stackoverflow.com/questions/43730887/android-recyclerview-adapter-is-giving-null-on-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!