【问题标题】:How do I assert that a scrollable TabLayout is currently showing a certain tab?如何断言可滚动的 TabLayout 当前正在显示某个选项卡?
【发布时间】:2022-01-15 02:34:59
【问题描述】:
【问题讨论】:
标签:
android-espresso
android-tablayout
android-viewpager2
【解决方案1】:
感谢Aaron's answer,我定义了withTabText(text:) 和isSelectedTab() 函数,现在我的测试读起来更流畅了,如下:
onView(withTabText("SomeText")).check(matches(isCompletelyDisplayed()))
onView(withTabText("SomeText")).check(matches(isSelectedTab()))
isSelectedTab()函数实现如下:
/**
* @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
}
}
withTabText(text:)函数实现如下:
/**
* @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
}
}
我已将这两个函数添加到 android-test-utils GitHub 存储库中的自定义视图匹配器集合中。
【解决方案2】:
您可以为标签创建自定义Matcher:
fun withTab(title: String) = withTab(equalTo(title))
fun withTab(title: Matcher<String>): Matcher<View> {
return object : BoundedMatcher<View, TabView>(TabView::class.java) {
override fun describeTo(description: Description) {
description.appendText("with tab: ")
title.describeTo(description)
}
override fun matchesSafely(item: TabView): Boolean {
return title.matches(item.tab?.text)
}
}
}
然后要查找当前是否显示选项卡,您可以方便地使用:
onView(withTab("tab text")).check(matches(isCompletelyDisplayed()))
如果您想断言当前是否选择了一个选项卡,您可以调整matchesSafely 以使用item.tab?.isSelected,或者简单地创建一个新的匹配器。
但是,如果屏幕上有多个TabLayout,则可能需要将匹配器与isDescendantOfA 或withParent 合成。