How to set current tab in viewpager with tablayout
Asked Answered
A

2

17

I have a custom viewpager (with swiping disabled for reasons) working with a tablayout. The content changes based on which tab is selected. I want to test this using espresso: 1) Click on a particular tab 2) Check some data in a particular page of the tab How can I do that. I am a novice to espresso

Augend answered 10/11, 2015 at 22:11 Comment(0)
C
23

There are several ways of doing this, an easy one is to select the element by the tab title, I use this code:

Matcher<View> matcher = allOf(withText("TAB TITLE"),
            isDescendantOfA(withId(R.id.customTab)));
onView(matcher).perform(click());
SystemClock.sleep(800); // Wait a little until the content is loaded

You only have to adapt the matcher to your layout. Then, check the content.

For example:

onView(withId(R.id.someId)).check(matches(isCompletelyDisplayed()));

or:

onView(withText(R.string.someText)).check(matches(isCompletelyDisplayed()));

You can find examples here in the Specifying a View Matcher section: http://developer.android.com/intl/es/training/testing/ui-testing/espresso-testing.html

If you are using a RecyclerView to show the content of the tabs have a look at this: Espresso RecyclerView inside ViewPager

Contend answered 12/5, 2016 at 15:48 Comment(5)
What if the tab has only an icon and no text, how to capture it? withIcon() does not exist in Espresso. Any other alternative?Littlest
In that case you can still use the withId, withTagValue or create a custom matcher instead of the withText oneContend
From my actual code I passed in a setTag() within my tabLayout.getTabAt(i).setTag(...) but withTagValue() takes a Matcher<Object> as parameter and not a string. Regarding withId(), tabLayout.getTabAt(i) does not have any method for setId(). I can only set the id of the whole layout and not the individual single tab.Littlest
You can use withTagValue this way: onView(withTagValue(is((Object) tagValueString))) using the Matcher.is method to find views with that tagContend
I implemented your suggestions but my test is failing. I opened the following question #51029455Littlest
S
-3

Espresso should be used when you clearly know what is expected in the UI and so you can verify the same.

In your case, to go to any tab, you can use view action to tap on that tab. To verify the data, first you should know what data is expected to be there on that tab and then just use matchers to check if they are displayed or not.

Silvasilvain answered 20/11, 2015 at 20:49 Comment(1)
This doesn't explain how to select a specific tab in a ViewPager.Agonist

© 2022 - 2024 — McMap. All rights reserved.