Updated 16 April 2019
In Espresso when we have to locate to a particular position of an element and there are multiple element of having same id then we can do it by the following approaches :-
In this we have to create a custom index :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public static Matcher<View> withIndex(final Matcher<View> matcher, final int index) { return new TypeSafeMatcher<View>() { int currentIndex = 0; @Override public void describeTo(Description description) { description.appendText("with index: "); description.appendValue(index); matcher.describeTo(description); } @Override public boolean matchesSafely(View view) { return matcher.matches(view) && currentIndex++ == index; } }; } |
And like this we have to use it :-
1 |
onView(withIndex(withId(R.id.button_btn), 0)).perform( click()); |
Here the “button_id” is the id where we want to perfom a click action and “0” is the index position of that element.
Then we using this class in code like this:-
1 2 |
onView(withId(R.id.my_recycler_view)).perform( RecyclerViewActions.actionOnItemAtPosition(0, MyViewAction.clickChildViewWithId(R.id.button_id))).perform(scrollTo(),click()); |
here “my_recycler_view” is the id of recycler view and “0” is the position where we want to click that button and “
button-id” is the id of the button on which we have to perform the click.
Here is the class “MyViewAction“:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public static class MyViewAction { public static ViewAction clickChildViewWithId(final int id) { return new ViewAction() { @Override public Matcher<View> getConstraints() { return null; } @Override public String getDescription() { return "Click on a child view with specified id."; } @Override public void perform(UiController uiController, View view) { View v = view.findViewById(id); v.performClick(); } }; } } |
By using this technique you can easily locate to your location When there are multiple same id buttons.
I hope this will help you when you face “multiple match” problem in Espresso.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.