Адаптер Android RecyclerView дает нуль при модульном тестировании

Я пытаюсь протестировать RecyclerView с AndroidJunit4, это мой тестовый код:

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)

В чем проблема в коде?


person dev_android    schedule 02.05.2017    source источник
comment
Можете ли вы опубликовать свой код ProductListActivity?   -  person Bartek Lipinski    schedule 04.05.2017


Ответы (1)


Судя по этой строке:

Ожидается: экземпляр com.kaushik.myredmart.adapter.ProductAdapter, но: null

Можно сделать вывод, что это:

RecyclerView.Adapter adapter = productRecyclerView.getAdapter();

возвращает null, что может произойти, если не было выполнено productRecyclerView.setAdapter(adapter).

Убедитесь, что вы правильно настраиваете адаптер в обратных вызовах жизненного цикла активности (например, в onCreate()). Мне кажется, вы создаете и настраиваете адаптер после некоторого действия/обратного вызова.

person azizbekian    schedule 04.05.2017