【问题标题】:Android Espresso check selected spinner textAndroid Espresso 检查选定的微调器文本
【发布时间】:2015-10-03 22:18:07
【问题描述】:

我的 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 contains "CCD"' 与所选视图不匹配。 预期:带有文本:包含“CCD”的字符串 得到:“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}"

【问题讨论】:

标签: android android-espresso


【解决方案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

【讨论】:

  • 这里的selectionText是什么??
  • 这是一个字符串 - 微调器文本,与用户可见的相同。
  • 如何在不使用这些访问器方法的情况下获取 Spinner 对象本身并按照自己的方式处理它?还是因为线程或其他标准 Android 借口而被禁止?
  • 不幸的是,此链接已损坏。 @Jonas 知道正确的链接应该是什么吗?
  • 找不到正确的链接了。在链接中有一个错误报告并修复它。通常只使用匹配器函数 withSpinnerText() 应该可以解决这些天的问题,链接中的详细信息只是附加的历史信息。很久以前 espresso 没有 withSpinnerText()。
【解决方案2】:

对我来说非常简单的解决方案.....无需为 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() 方法。

【讨论】:

  • YouCustomClass 是适配器类,item 是适配器中的一个项目?
  • 什么是YourCustomClass?它像类模型吗?
【解决方案4】:

这对我有用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多