6

Próbuję przetestować RecyclerView z AndroidJunit4, to jest mój kodu testu:Android RecyclerView Adapter daje zerowy na testowanie jednostkowe

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

    } 
} 

jestem w obliczu problemu, by sprawdzić zasilacz. Chociaż productRecyclerView przechodzi not null test i wystąpienie RecyclerView, jest następujący błąd w ostatnim wierszu:

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) 

Jaki jest problem w kodzie?

+0

Czy możesz opublikować swój kod 'ProductListActivity'? –

Odpowiedz

9

Sądząc po tej linii:

spodziewanych: wystąpienie com.kaushik.myredmart.adapter.ProductAdapter ale: null

Jeden może stwierdzić, że w ten sposób:

RecyclerView.Adapter adapter = productRecyclerView.getAdapter(); 

zwraca null, co może się zdarzyć, gdy nie zostało wykonane productRecyclerView.setAdapter(adapter).

Upewnij się, że prawidłowo ustawiłeś adapter w wywołaniach zwrotnych cyklu życia aktywności (tj. W onCreate()). Wydaje mi się, że tworzysz i ustawiasz adapter po pewnym działaniu/wywołaniu.

-1

Jak wspomniano przez @azizbekian, powinieneś ustawić adapter w onCreate() aktywności.

Powiązane problemy