Can one test Support v7 SearchView with Espresso on Android
For some reason on click()
doesn't work for me.
I used this extension of expression for searchViews, written in kotlin:
class SearchViewActionExtension {
companion object {
fun submitText(text: String): ViewAction {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return allOf(isDisplayed(), isAssignableFrom(SearchView::class.java))
}
override fun getDescription(): String {
return "Set text and submit"
}
override fun perform(uiController: UiController, view: View) {
(view as SearchView).setQuery(text, true) //submit=true will fire search
}
}
}
fun typeText(text: String): ViewAction {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return allOf(isDisplayed(), isAssignableFrom(SearchView::class.java))
}
override fun getDescription(): String {
return "Set text"
}
override fun perform(uiController: UiController, view: View) {
(view as SearchView).setQuery(text, false)
}
}
}
}
}
By calling setQuery
with true for submit parameter it fires search right after.
Usage:
onView(withId(R.id.search_box))
.perform(SearchViewActionExtension.submitText("search text"))
The solution depends on the initial state of the SearchView
.If it is collapsed, you have to open it first:
onView(withId(R.id.your_search_menu_id)).perform(click());
Then you can type into it.
There are two ways:
By search autocomplete id, which is public
onView(withId(android.support.design.R.id.search_src_text)).perform(typeText("something"));
By using the fact, that it is
AutoCompleteTextView
onView(isAssignableFrom(AutoCompleteTextView.class)).perform(typeText("something"));