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

标签 android android-spinner android-testing android-espresso

我有自定义布局的微调器:

<?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 中的值是否与特定文本匹配。 是否可以在不实现自定义 Matcher 类的情况下执行此操作?

我的简单测试:

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

}

最佳答案

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

 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() 方法。

关于安卓 Espresso : How to match text on custom spinner selected item layout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34581576/

相关文章:

android - Imageview拖放到recyclerview Android

android - 创建具有自定义设计的选项卡小部件

android - SpinnerAdapter 中 getView 和 getDropDownView 的区别

android - actionbar setnavigationmode 弃用

android - 无法在 Android Espresso 测试中获取正在测试的 Activity

android - 应用强制停止后手动重新启用辅助功能服务不会重新启动

android - 如何仅使用其内容 Uri 强制更新文件的 MediaStore

Android 自定义微调器在 17 台设备上变黑

Android Espresso Ui 测试验证 ActionPage 的标签文本

Android Sqlite数据库测试攻略