Android Espresso:如何匹配自定义微调器所选项目布局上的文本?

Android Espresso: How to match text on custom spinner selected item 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>

并且我需要检查所选项目 R.id.tv_text 中的值是否与特定文本匹配。 是否可以在不实施自定义匹配器的情况下执行此操作 class ?

我的简单测试:

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

}

我没有找到比创建自定义匹配器更简单的方法,该匹配器在 Spinner 所选项目的任何 TextView(或其继承者)中查找特定文本。有一个我的自定义匹配器:https://gist.github.com/igorokr/5f3db37f0b9eb8b2feae

我也使用自定义匹配器实现了这一点。但我使用了一个不那么冗长的匹配器,也许它对某人有帮助:

 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) {

        }
    };
}

那么您必须在您的自定义 class 上覆盖 toString() 方法。

对我来说非常简单的解决方案.....无需使用匹配器 对于 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"))));