Testing RecyclerView if it has data with Espresso

萝らか妹 提交于 2020-01-13 09:54:09

问题


I need to write a test to click, let's say on the first item in my RecyclerView. At some cases the RecyclerView will be empty and therefore if I click on the position with 0 index it will fail. How do I write a test like this? To check first if the recyclerView not empty and then click on the specific position?


回答1:


There are a little bit different scenarios in question and in the comment.

Let's implement the next test scenario: If recycler view does not contain anything, do nothing. If recycler view has at least one element, click on the first.

@Rule
public final ActivityTestRule<YourActivity> mActivityRule = new ActivityTestRule<>(YourActivity.class);

@Test
public void testSample(){
    if (getRVcount() > 0){
        onView(withId(R.id.our_recycler_view)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
    }
}

private int getRVcount(){
    RecyclerView recyclerView = (RecyclerView) mActivityRule.getActivity().findViewById(R.id.our_recycler_view);
    return recyclerView.getAdapter().getItemCount();
}



回答2:


For your case, I think it's better to check with check method. An example is given below.

@Test
 fun mainActivityTest() {   
    val yourRecycler = onView(
        allOf(

            childAtPosition(
                withClassName(`is`("androidx.constraintlayout.widget.ConstraintLayout")),
                0
            ),
            instanceOf(RecyclerView::class.java)
        )
    )
    yourRecycler.check { view, noViewFoundException ->
                noViewFoundException?.apply {
                    throw this
                }
                assertTrue(view is RecyclerView &&
                    view.adapter != null && view.adapter?.itemCount?:-1 > 0
                )

            }
    }


来源:https://stackoverflow.com/questions/40140700/testing-recyclerview-if-it-has-data-with-espresso

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