Espresso - 如何点击随机的 RecyclerView 项目?

Espresso - How to click on a random RecyclerView item?

有几篇文章展示了如何使用 Espresso 单击 RecyclerView 中的某个 固定 项目,例如:

How to click on an item inside a RecyclerView in Espresso


示例:

//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 中的随机项怎么办?

使用ActivityTestRulegetActivity()方法。

您将能够使用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);
    }

}