How to type text on a SearchView using espresso

2019-06-08 14:35发布

TypeText doesn't seem to work with SearchView.

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

gives the error:

Error performing 'type text(how is the weather?)' on view 'with id:../yt_search_box'

1条回答
何必那么认真
2楼-- · 2019-06-08 15:22

For anyone that bump into this problem too, the solution is to write a ViewAction for the type SearchView, since the typeText only supports TextEditView

Here my solution:

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);
        }
    };
}
查看更多
登录 后发表回答