In Espresso, how to avoid AmbiguousViewMatcherException when multiple views match

AndroidAndroid Espresso

Android Problem Overview


Having gridView which has some images. The gridView's cell comes out from same predefined layout, which has same id and desc.

> R.id.item_image == 2131493330

onView(withId(is(R.id.item_image))).perform(click());

Since all cells in the grid have same id, it got AmbiguousViewMatcherException. How to just pick up first one or any of one of them? Thanks!

> android.support.test.espresso.AmbiguousViewMatcherException: 'with id: is <2131493330>' matches multiple views in the hierarchy. Problem views are marked with 'MATCHES' below.

> +------------->ImageView{id=2131493330, res-name=item_image, desc=Image, visibility=VISIBLE, width=262, height=262, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0} MATCHES

> +------------->ImageView{id=2131493330, res-name=item_image, desc=Image, visibility=VISIBLE, width=262, height=262, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0} MATCHES |

Android Solutions


Solution 1 - Android

EDIT: Someone mentioned in the comments that withParentIndex is now available, give that a try first before using the custom solution below.

I was amazed that I couldn't find a solution by simply providing an index along with a matcher (i.e. withText, withId). The accepted answer only solves the problem when you're dealing with onData and ListViews.

If you have more than one view on the screen with the same resId/text/contentDesc, you can choose which one you want without causing an AmbiguousViewMatcherException by using this custom matcher:

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;
        }
    };
}

For example:

onView(withIndex(withId(R.id.my_view), 2)).perform(click());

will perform a click action on the third instance of R.id.my_view.

Solution 2 - Android

Not completely related to grid view situation but you can use hamcrest allOf matchers to combine multiple conditions:

import static org.hamcrest.CoreMatchers.allOf;

onView(allOf(withId(R.id.login_password), 
             withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)))
        .check(matches(isCompletelyDisplayed()))
        .check(matches(withHint(R.string.password_placeholder)));

Solution 3 - Android

You should use onData() to operate on GridView:

onData(withId(R.id.item_image))
        .inAdapterView(withId(R.id.grid_adapter_id))
        .atPosition(0)
		.perform(click());

This code will click on the image inside first item in GridView

Solution 4 - Android

Tried @FrostRocket answer as was looking most promissing but needed to add some customisations:

public static Matcher<View> withIndex(final Matcher<View> matcher, final int index) {
    return new TypeSafeMatcher<View>() {
        int currentIndex;
        int viewObjHash;

        @SuppressLint("DefaultLocale") @Override
        public void describeTo(Description description) {
            description.appendText(String.format("with index: %d ", index));
            matcher.describeTo(description);
        }

        @Override
        public boolean matchesSafely(View view) {
            if (matcher.matches(view) && currentIndex++ == index) {
                viewObjHash = view.hashCode();
            }
            return view.hashCode() == viewObjHash;
        }
    };
}

Solution 5 - Android

I created a ViewMatcher which matches the first view it finds. Maybe it is helpful for somebody. E.g. when you don't have an AdapterView to use onData() on.

/**
 * Created by stost on 15.05.14.
 * Matches any view. But only on first match()-call.
 */
public class FirstViewMatcher extends BaseMatcher<View> {


   public static boolean matchedBefore = false;

   public FirstViewMatcher() {
       matchedBefore = false;
   }

   @Override
   public boolean matches(Object o) {
       if (matchedBefore) {
           return false;
       } else {
           matchedBefore = true;
           return true;
       }
   }

   @Override
   public void describeTo(Description description) {
       description.appendText(" is the first view that comes along ");
   }

   @Factory
   public static <T> Matcher<View> firstView() {
       return new FirstViewMatcher();
   }
}


Use it like this:

 onView(FirstViewMatcher.firstView()).perform(click());

Solution 6 - Android

Cases:

onView( withId( R.id.songListView ) ).perform( RealmRecyclerViewActions.scrollTo( Matchers.first(Matchers.withTextLabeled( "Love Song"))) );
onView( Matchers.first(withText( "Love Song")) ).perform( click() );

inside my Matchers.class

public static Matcher<View> first(Matcher<View> expected ){

    return new TypeSafeMatcher<View>() {
        private boolean first = false;

        @Override
        protected boolean matchesSafely(View item) {

            if( expected.matches(item) && !first ){
                return first = true;
            }

            return false;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("Matcher.first( " + expected.toString() + " )" );
        }
    };
}

Solution 7 - Android

Not specifically related to grid view but I had a similar problem where both an element on my RecyclerView and on my root layout had the same id and were both displayed to the screen. What helped me to solve it was to check descendancy such as:

 onView(allOf(withId(R.id.my_view), not(isDescendantOfA(withId(R.id.recyclerView))))).check(matches(withText("My Text")));

enter image description here

Solution 8 - Android

At latest * Run -> Record Espresso Test

By Click on the Same ID View with different position generate different Code for them so try it.

Its Actually Resolve these problem.

Solution 9 - Android

You can simply make NthMatcher like:

   class NthMatcher internal constructor(private val id: Int, private val n: Int) : TypeSafeMatcher<View>(View::class.java) {
        companion object {
            var matchCount: Int = 0
        }
        init {
            var matchCount = 0
        }
        private var resources: Resources? = null
        override fun describeTo(description: Description) {
            var idDescription = Integer.toString(id)
            if (resources != null) {
                try {
                    idDescription = resources!!.getResourceName(id)
                } catch (e: Resources.NotFoundException) {
                    // No big deal, will just use the int value.
                    idDescription = String.format("%s (resource name not found)", id)
                }

            }
            description.appendText("with id: $idDescription")
        }

        public override fun matchesSafely(view: View): Boolean {
            resources = view.resources
            if (id == view.id) {
                matchCount++
                if(matchCount == n) {
                    return true
                }
            }
            return false
        }
    }

Declare like this:

fun withNthId(resId: Int, n: Int) = CustomMatchers.NthMatcher(resId, n)

And use like this:

onView(withNthId(R.id.textview, 1)).perform(click())

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlannyfView Question on Stackoverflow
Solution 1 - Android0xMatthewGrovesView Answer on Stackoverflow
Solution 2 - AndroidShubham ChaudharyView Answer on Stackoverflow
Solution 3 - AndroiddenysView Answer on Stackoverflow
Solution 4 - Androidfada21View Answer on Stackoverflow
Solution 5 - AndroidStefanToView Answer on Stackoverflow
Solution 6 - AndroidJuan MendezView Answer on Stackoverflow
Solution 7 - AndroidFrancislainy CamposView Answer on Stackoverflow
Solution 8 - AndroidPinak GauswamiView Answer on Stackoverflow
Solution 9 - AndroidJohnView Answer on Stackoverflow