I'm trying to check if my fragment is visible after performing a click on my tab from my tabLayout which has been set up with view pager.
This is my actual activity code, inside my activity onCreate method:
mViewPager = findViewById(R.id.contentFrameLayout);
mViewPager.setAdapter(mSectionPageAdapter);
mViewPager.setPagingEnabled(false);
//Set up the tab layout to display tabs
tabLayout = findViewById(R.id.homeTabs);
tabLayout.setupWithViewPager(mViewPager);
for (int i = 0; i< tabLayout.getTabCount(); i++) {
TabLayout.Tab mTab = tabLayout.getTabAt(i);
if (mTab != null) {
switch (i){
case 0:
mTab.setTag(WFragment.class.toString());
mTab.setIcon(R.drawable.home_icon_svg);
break;
case 1:
mTab.setTag(MFragment.class.toString());
mTab.setIcon(R.drawable.l_svg);
break;
case 2:
//etc..
}
}
}
Here is my instrumentation test:
@Test
public void checkIfMFragmentIsVisible() {
Matcher<View> matcher = allOf(withTagValue(is((Object) MFragment.class.toString())),
isDescendantOfA(withId(R.id.homeTabs)));
onView(matcher).perform(click());
onView(withId(R.id.mFragmentLayout)).check(matches(isCompletelyDisplayed()));
}
I used information from this link which helped me getting started with creating a matcher and performing a click. However, my test is failing with the following error:
android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: (with tag value: is "class com.test.solution.fragments.MFragment" and is descendant of a: with id: 2131296345)
If the target view is not part of the view hierarchy, you may need to use Espresso.onData to load it from one of the following AdapterViews:com.google.maps.api.android.lib6.impl.ce{d55b63a G.ED..C.. ......I. 0,0-0,0}
SUCCESSFUL INSTRUMENTATION TEST:
I tried a dummy test by adding the following in my tabs in my activity:
TabLayout.Tab mTab = tabLayout.getTabAt(i);
if (mTab != null) {
switch (i){
case 0:
mTab.setText("case 0");
//etc..
case 1:
mTab.setText("case 1");
//etc..
case 2:
//etc..
And in my Instrumentation Test:
@Test
public void checkIfMFragmentIsVisible() {
Matcher<View> matcher = allOf(withText("case 1"),
isDescendantOfA(withId(R.id.homeTabs)));
onView(matcher).perform(click());
onView(withId(R.id.mFragmentLayout)).check(matches(isCompletelyDisplayed()));
}
This test was successful, however, I do not want to use a text in my activity, but I want to use a tag or something else.