Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type text on a SearchView using espresso

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'

like image 558
MiguelSlv Avatar asked Dec 30 '17 19:12

MiguelSlv


Video Answer


2 Answers

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);
        }
    };
}
like image 100
MiguelSlv Avatar answered Oct 16 '22 01:10

MiguelSlv


@MiguelSlv answer above, converted to 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)
        }
    }
}
like image 25
hyena Avatar answered Oct 16 '22 01:10

hyena