Android Espresso 检查选定的微调器文本

Android Espresso check selected spinner text

我的 Espresso 测试中有这段代码

onView(withId(R.id.src))
    .perform(click());
onData(hasToString(startsWith("CCD")))
    .perform(click());
onView(withId(R.id.src))
    .check(matches(withText(containsString("CCD"))));

我想要做的是单击 Spinner 中的项目并检查它是否确实在 Spinner 中被选中。

但是我收到这个错误:

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with text: a string containing "CCD"' doesn't match the selected view. Expected: with text: a string containing "CCD" Got: "AppCompatSpinner{id=2131558533, res-name=src, visibility=VISIBLE, width=528, height=163, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}"

withText()替换为withSpinnerText()

onView(withId(spinnerId)).perform(click());
onData(allOf(is(instanceOf(String.class)), is(selectionText))).perform(click());
onView(withId(spinnerId)).check(matches(withSpinnerText(containsString(selectionText))));

参考:https://code.google.com/p/android-test-kit/issues/detail?id=85

对于自定义适配器,我让您创建了一个自定义匹配器:

 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"))));

这对我有用

 private void selectSpinnerItem(final int resId, final String selection) {
    onView(withId(resId)).perform(click());
    onData(hasToString(selection)).perform(click());
    onView(withId(resId)).check(matches(withSpinnerText(containsString(selection))));
}