Reputation: 35
Within an activity, I have a custom recycler view that contains 2 textviews and 2 buttons as shown below.
The id for the recycling bin icon button is deleteButton. I would like to access this button within espresso testing so that I can mock a click.
Two methods that I have attempted and failed are shown below:
onView(withId(R.id.basket))
.perform(actionOnItemAtPosition(4, click() ));
onView(withText("Cherry"))
.perform(
RecyclerViewActions.actionOnItem(
hasDescendant(withId(R.id.deleteButton)),
ViewActions.click()
)
);
Thank you for any help in advance.
Upvotes: 2
Views: 595
Reputation: 3894
One way to click on a view inside a RecyclerView
item view is by creating a custom view action:
public static ViewAction actionOnItemView(Matcher<View> matcher, ViewAction action) {
return new ViewAction() {
@Override public String getDescription() {
return String.format("performing ViewAction: %s on item matching: %s", action.getDescription(), StringDescription.asString(matcher));
}
@Override public Matcher<View> getConstraints() {
return allOf(withParent(isAssignableFrom(RecyclerView.class)), isDisplayed());
}
@Override public void perform(UiController uiController, View view) {
List<View> results = new ArrayList<>();
for (View v : TreeIterables.breadthFirstViewTraversal(view)) {
if (matcher.matches(v)) results.add(v);
}
if (results.isEmpty()) {
throw new RuntimeException(String.format("No view found %s", StringDescription.asString(matcher)));
} else if (results.size() > 1) {
throw new RuntimeException(String.format("Ambiguous views found %s", StringDescription.asString(matcher)));
}
action.perform(uiController, results.get(0));
}
};
}
Then use one of the RecyclerViewActions on your RecyclerView
, then actionOnItemView
as subsequent action on the item view if successful:
ViewAction itemViewAction = actionOnItemView(withId(R.id.deleteButton), click());
onView(withId(your_recycler_view)).perform(actionOnItemAtPosition(4, itemViewAction));
Upvotes: 2