Search code examples
android-espressoandroid-tablayoutandroid-viewpager2

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


I am displaying a TabLayout and connecting it to a ViewPager2 object (by means of the TabLayoutMediator class). The TabLayout has a tabMode of scrollable and contains more tabs than can fit in the screen at once. I want to assert that a certain one of the tabs is visible and selected when my activity or fragment is rendered. How do I do this?


Solution

  • You can create a custom Matcher for the tabs:

    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)
            }
        }
    }
    

    Then to find if a tab is currently showing, you can conveniently do it with:

    onView(withTab("tab text")).check(matches(isCompletelyDisplayed()))
    

    If you want to assert if a tab is currently selected, you can either adjust matchesSafely to work with item.tab?.isSelected, or simply create a new matcher.

    However if you have more than one TabLayout on the screen, then you may need to composite your matcher with isDescendantOfA or withParent.