我如何断言可滚动的 TabLayout 当前正在显示某个选项卡?

How do I assert that a scrollable TabLayout is currently showing a certain tab?

我正在显示一个 TabLayout and connecting it to a ViewPager2 object (by means of the TabLayoutMediator class). The TabLayout has a tabMode of scrollable,其中包含的选项卡多于屏幕一次可以容纳的选项卡。我想断言,当我的 activity 或片段被呈现时,某个选项卡是可见的并被选中。我该怎么做?

感谢 ,我定义了 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 存储库中我的自定义视图匹配器集合中。

您可以为选项卡创建自定义 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,那么您可能需要将匹配器与 isDescendantOfAwithParent 组合。