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

问题描述 投票:21回答:3

我的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:'带有文本:包含“ CCD”的字符串”与所选视图不匹配。预期值:带文字:包含“ CCD”的字符串得到了:“ AppCompatSpinner {id = 2131558533,res-name = src,可见性= VISIBLE,宽度= 528,高度= 163,has-focus = false,has-focusable = true,has-window-focus = true,可点击= true,已启用= 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,子计数= 1}“

android android-espresso
3个回答
66
投票

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


7
投票

非常简单的解决方案,对我来说很有效...,而无需为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"))));

3
投票

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

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

        }
    };
}

然后,您必须在自定义类上重写toString()方法。

© www.soinside.com 2019 - 2024. All rights reserved.