Android RecyclerView Adapter gives null value for unit testing

I am trying to test RecyclerView with AndroidJunit4, this 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 have a problem checking the adapter. Although productRecyclerView passes a non-null test and a RecyclerView instance, it contains an error in the 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 with the code?

+6
source share
2 answers

Judging by this line:

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

We can conclude that this:

RecyclerView.Adapter adapter = productRecyclerView.getAdapter();

returns nullwhat might happen when it was not executed productRecyclerView.setAdapter(adapter).

, (.. onCreate()). , / .

+10

@azizbekian, onCreate() .

-1

Source: https://habr.com/ru/post/1016923/


All Articles