使用Espresso测试RecyclerView是否有数据 [英] Testing RecyclerView if it has data with Espresso
问题描述
我需要编写一个单击测试,让我们说一下RecyclerView中的第一项.在某些情况下,RecyclerView将为空,因此,如果我单击具有0
索引的位置,它将失败.我该如何编写这样的测试?要先检查recyclerView
是否不为空,然后单击特定位置?
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?
推荐答案
问题和评论中存在一些不同的情况.
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();
}
这篇关于使用Espresso测试RecyclerView是否有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!