【问题标题】:How do I assert that a scrollable TabLayout is currently showing a certain tab?如何断言可滚动的 TabLayout 当前正在显示某个选项卡?
【发布时间】:2022-01-15 02:34:59
【问题描述】:

我正在显示一个TabLayout 并将其连接到一个ViewPager2 对象(通过TabLayoutMediator 类)。 TabLayout 有一个 tabModescrollable,并且包含的​​选项卡数量超过了一次可以在屏幕中显示的数量。我想断言,在呈现我的活动或片段时,某个选项卡是可见的并被选中。我该怎么做?

【问题讨论】:

    标签: 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 存储库中的自定义视图匹配器集合中。

    【讨论】:

    • 你能检查一下这个issue
    【解决方案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,则可能需要将匹配器与isDescendantOfAwithParent 合成。

    【讨论】:

    • 你能检查一下这个issue
    猜你喜欢
    • 2018-01-03
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 2020-01-11
    相关资源
    最近更新 更多