Espresso - How To Click On A Random Recyclerview Item?
There are a few posts that show how can you click a certain fixed item in the RecyclerView with Espresso, like: How to click on an item inside a RecyclerView in Espresso Using Espr
Solution 1:
Use the getActivity()
method of ActivityTestRule.
You will be able to use findViewById()
(as in any other context) and handle the RecyclerView instance.
Example:
@RunWith(AndroidJUnit4.class)publicclassRandomBehaviorTest {
//This rule provides functional testing of a single activity.@Rulepublic ActivityTestRule<MainActivity> mActivityRule =
newActivityTestRule<>(MainActivity.class);
@TestpublicvoidclickRandomItem() {
//Magic happeningintx= getRandomRecyclerPosition(R.id.a_main_recycler);
onView(withId(R.id.a_main_recycler))
.perform(RecyclerViewActions
.actionOnItemAtPosition(x, click()));
}
privateintgetRandomRecyclerPosition(int recyclerId) {
Randomran=newRandom();
//Get the actual drawn RecyclerView RecyclerViewrecyclerView= (RecyclerView) mActivityRule
.getActivity().findViewById(recyclerId);
//If the RecyclerView exists, get the item count from the adapterintn= (recyclerView == null)
? 1
: recyclerView.getAdapter().getItemCount();
//Return a random number from 0 (inclusive) to adapter.itemCount() (exclusive) return ran.nextInt(n);
}
}
Post a Comment for "Espresso - How To Click On A Random Recyclerview Item?"