Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Espresso match first element found when many are in hierarchy

I'm trying to write an espresso function to match the first element espresso finds according to my function, even when multiple matching items are found.

Ex: I have a list view with cells which contain item price. I want to be able to switch the currency to Canadian dollars and verify item prices are in CAD.

I'm using this function:

    onView(anyOf(withId(R.id.product_price), withText(endsWith("CAD"))))
        .check(matches(
                isDisplayed()));

This throws the AmbiguousViewMatcherException.

In this case, I don't care how many or few cells display CAD, I just want to verify it is displayed. Is there way to make espresso pass this test as soon as it encounters an object meeting the parameters?

like image 912
Bebop_ Avatar asked Sep 03 '15 23:09

Bebop_


2 Answers

You should be able to create a custom matcher that only matches on the first item with the following code:

private <T> Matcher<T> first(final Matcher<T> matcher) {
    return new BaseMatcher<T>() {
        boolean isFirst = true;

        @Override
        public boolean matches(final Object item) {
            if (isFirst && matcher.matches(item)) {
                isFirst = false;
                return true;
            }

            return false;
        }

        @Override
        public void describeTo(final Description description) {
            description.appendText("should return first matching item");
        }
    };
}
like image 180
appmattus Avatar answered Nov 08 '22 01:11

appmattus


I created this matcher in case you have many elements with same characteristics like same id, and if you want not just the first Element but instead want an specific Element. Hope this helps:

    private static Matcher<View> getElementFromMatchAtPosition(final Matcher<View> matcher, final int position) {
    return new BaseMatcher<View>() {
        int counter = 0;
        @Override
        public boolean matches(final Object item) {
            if (matcher.matches(item)) {
                if(counter == position) {
                    counter++;
                    return true;
                }
                counter++;
            }
            return false;
        }

        @Override
        public void describeTo(final Description description) {
            description.appendText("Element at hierarchy position "+position);
        }
    };
}

Example:

You have many buttons with same id given from a library you are using, you want to pick the second button.

  ViewInteraction colorButton = onView(
            allOf(
                    getElementFromMatchAtPosition(allOf(withId(R.id.color)), 2),
                    isDisplayed()));
    colorButton.perform(click());
like image 10
LinuxFelipe-COL Avatar answered Nov 08 '22 00:11

LinuxFelipe-COL