有一些帖子显示如何点击带有Espresso的RecyclerView中的某个已修复项目,例如:
How to click on an item inside a RecyclerView in Espresso
Using Espresso to click view inside RecyclerView item
示例:
//Change the 0 with any other number, will be the position of the item clicked.
onView(withId(R.id.a_main_recycler))
.perform(RecyclerViewActions
.actionOnItemAtPosition(0, click()));
但是,如果您想点击RecyclerView中的随机项,该怎么办?
答案 0 :(得分:3)
使用ActivityTestRule的getActivity()
方法。
您将能够使用findViewById()
(与任何其他上下文一样)和处理 RecyclerView实例。
示例:强>
@RunWith(AndroidJUnit4.class)
public class RandomBehaviorTest {
//This rule provides functional testing of a single activity.
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<>(MainActivity.class);
@Test
public void clickRandomItem() {
//Magic happening
int x = getRandomRecyclerPosition(R.id.a_main_recycler);
onView(withId(R.id.a_main_recycler))
.perform(RecyclerViewActions
.actionOnItemAtPosition(x, click()));
}
private int getRandomRecyclerPosition(int recyclerId) {
Random ran = new Random();
//Get the actual drawn RecyclerView
RecyclerView recyclerView = (RecyclerView) mActivityRule
.getActivity().findViewById(recyclerId);
//If the RecyclerView exists, get the item count from the adapter
int n = (recyclerView == null)
? 1
: recyclerView.getAdapter().getItemCount();
//Return a random number from 0 (inclusive) to adapter.itemCount() (exclusive)
return ran.nextInt(n);
}
}