如何使用 espresso 在 SearchView 上输入文本

问题描述 投票:0回答:6

TypeText
似乎不适用于
SearchView

onView(withId(R.id.yt_search_box))
            .perform(typeText("how is the weather?"));

给出错误:

在视图“id:../yt_search_box”上执行“输入文本(天气怎么样?)”时出错

android searchview android-espresso
6个回答
16
投票

对于也遇到此问题的任何人,解决方案是为 SearchView 类型编写 ViewAction,因为 typeText 仅支持 TextEditView

这是我的解决方案:

public static ViewAction typeSearchViewText(final String text){
    return new ViewAction(){
        @Override
        public Matcher<View> getConstraints() {
            //Ensure that only apply if it is a SearchView and if it is visible.
            return allOf(isDisplayed(), isAssignableFrom(SearchView.class));
        }

        @Override
        public String getDescription() {
            return "Change view text";
        }

        @Override
        public void perform(UiController uiController, View view) {
            ((SearchView) view).setQuery(text,false);
        }
    };
}

10
投票

@MiguelSlv 上面的答案,转换为 kotlin

fun typeSearchViewText(text: String): ViewAction {
    return object : ViewAction {
        override fun getDescription(): String {
            return "Change view text"
        }

        override fun getConstraints(): Matcher<View> {
            return allOf(isDisplayed(), isAssignableFrom(SearchView::class.java))
        }

        override fun perform(uiController: UiController?, view: View?) {
            (view as SearchView).setQuery(text, false)
        }
    }
}

4
投票

这对我有用:

onView(withId(R.id.search_src_text)).perform(typeText("how is the weather?"))

3
投票

根据 César Noreña 的回复,我设法在搜索字段中插入文本。 首先,我单击我的视图,然后在 Android 搜索视图 id 上输入文本。

onView(withId(R.id.my_own_search_menu_id)).perform(click());
onView(withId(R.id.search_src_text)).perform(typeText("how is the weather?"))

SearchView 的 X 按钮也有 ID search_close_btn

onView(withId(R.id.search_close_btn)).perform(click()); // first time erase the content
onView(withId(R.id.search_close_btn)).perform(click()); // second time close the SearchView

0
投票

您可以使用Resource#getSystem来获取View

Resources.getSystem().getIdentifier("search_src_text",
    "id", "android")


onView(withId(Resources.getSystem().getIdentifier("search_src_text",
"id", "android"))).perform(clearText(),typeText("enter the text"))
.perform(pressKey(KeyEvent.KEYCODE_ENTER))

0
投票

要在工具栏的搜索视图中输入文本,您可以在测试中使用以下代码

onView(
        withId(R.id.search)
    ).perform(click())
//This is the id of the search icon

onView(
        instanceOf(SearchAutoComplete::class.java)
    ).perform(typeText("abc"))

这将在工具栏的搜索视图中键入文本

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