Espresso - How to click on a random RecyclerView item?

眉间皱痕 提交于 2019-12-13 00:48:32

问题


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 Espresso to click view inside RecyclerView item


Example:

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

But, what if you want to click on a random item in the RecyclerView?


回答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)
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);
    }

}


来源:https://stackoverflow.com/questions/35306033/espresso-how-to-click-on-a-random-recyclerview-item

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