Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Espresso: How to match text on custom spinner selected item layout?

I have spinner with custom layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="60dp"
        android:layout_height="60dp" />
    <TextView
        android:id="@+id/tv_text"
        android:textColor="#FFFFFF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

And I need to check if value in R.id.tv_text of selected item match with specific text. Is it possible to do this without implement custom Matcher class ?

My simple test:

@SmallTest
public class CategoryTest {

    public static final String TEXT_TO_MATCH = "Spinner item text";

    @Test
    public void testCreate() {
        ...
        onView(withId(R.id.spn_tt)).perform(click()); // open spinner
        onView(allOf(withId(R.id.tv_text), withText(TEXT_TO_MATCH))).perform(click()); // find item by text and click
        onView(withId(R.id.spn_tt)).check(matches(withTextInSpinnerSelectedView(TEXT_TO_MATCH))); // check if right item selected by text
    }

}
like image 460
IgorOK Avatar asked Oct 12 '25 20:10

IgorOK


2 Answers

I have archieved that using a custom matcher too. But i have used a less verbose matcher, maybe it helps someone:

 onView(withId(R.id.spinner)).perform(click());
 onData(allOf(is(instanceOf(YourCustomClass.class)), withMyValue("Open"))).perform(click());


public static <T> Matcher<T> withMyValue(final String name) {
    return new BaseMatcher<T>() {
        @Override
        public boolean matches(Object item) {
            return item.toString().equals(name);
        }

        @Override
        public void describeTo(Description description) {

        }
    };
}

Then you must override toString() method on your custom class.

like image 142
Renato Probst Avatar answered Oct 14 '25 14:10

Renato Probst


Really simple solution that worked out for me .....without using matcher for CustomSpinner

onView(withId(R.id.custom_spinner)).perform(click());
onData(anything()).atPosition(1).perform(click());
onView(withId(R.id.custom_spinner)).check(matches(withSpinnerText(containsString("yourstring"))));
like image 22
ArpitA Avatar answered Oct 14 '25 13:10

ArpitA