Denys P.
Denys P.

Reputation: 266

RecyclerView espresso test click() not working

I faced with strange espresso instrumentation test behavior. Clicking on recycler view's item not working.

Click not happened here:

onView(withId(R.id.recyclerView)).perform(actionOnItemAtPosition(0, click()));

But this workaround works:

onView(withId(R.id.recyclerView)).perform(actionOnItemAtPosition(0, recyclerClick()));

// ...

public static ViewAction recyclerClick() {
    return new ViewAction() {

        @Override
        public Matcher<View> getConstraints() {
            return any(View.class);
        }

        @Override
        public String getDescription() {
            return "performing click() on recycler view item";
        }

        @Override
        public void perform(UiController uiController, View view) {
            view.performClick();
        }
    };
}

Is this Espresso or RecyclerView issue?

Upvotes: 2

Views: 5467

Answers (2)

riwnodennyk
riwnodennyk

Reputation: 8258

Should be nothing to do with RecyclerView specifically. What Espresso does with its ViewActions.click() implementation is sending the MotionEvent to the center of the target view. Make sure no child intercepts it.

Upvotes: 4

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363815

You can use the RecyclerViewActions

Just use:

onView(withId(R.id.recyclerView)).perform(
            RecyclerViewActions.actionOnItemAtPosition(0, click()));

For example:

@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
  @Rule
  public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule<>(MainActivity.class);

  @Test
  public void clickItem() {
    onView(withId(R.id.recycler_view))
        .perform(RecyclerViewActions.actionOnItemAtPosition(o, click()));

    onView(withId(R.id.text))
        .check(matches(withText("XX")))
        .check(matches(isDisplayed()));
  }
}

Upvotes: 1

Related Questions