Thanks to Aaron's answer, I've defined withTabText(text:) and isSelectedTab() functions and my test's are now reading more fluently, as follows:
onView(withTabText("SomeText")).check(matches(isCompletelyDisplayed()))
onView(withTabText("SomeText")).check(matches(isSelectedTab()))
The isSelectedTab() function is implemented as follows:
/**
* @return A matcher that matches a [TabLayout.TabView] which is in the selected state.
*/
fun isSelectedTab(): Matcher<View> =
object : BoundedMatcher<View, TabLayout.TabView>(TabLayout.TabView::class.java) {
override fun describeTo(description: Description) {
description.appendText("TabView is selected")
}
override fun matchesSafely(tabView: TabLayout.TabView): Boolean {
return tabView.tab?.isSelected == true
}
}
The withTabText(text:) function is implemented as follows:
/**
* @param text The text to match on.
* @return A matcher that matches a [TabLayout.TabView] which has the given text.
*/
fun withTabText(text: String): Matcher<View> =
object : BoundedMatcher<View, TabLayout.TabView>(TabLayout.TabView::class.java) {
override fun describeTo(description: Description) {
description.appendText("TabView with text $text")
}
override fun matchesSafely(tabView: TabLayout.TabView): Boolean {
return text == tabView.tab?.text
}
}
I've added both of these functions to my collection of custom view matchers in the android-test-utils GitHub repo.