我想要检查在点击标签页后,我的片段是否可见。标签页是通过视图分页设置的。
这是我的实际活动代码,在活动的onCreate方法中:
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..
}
}
}
这是我的仪器测试:
@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()));
}
我使用了这个链接中的信息,帮助我开始创建匹配器并执行点击操作。然而,我的测试失败,并出现以下错误:
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}
成功的仪器测试:
我在我的活动选项卡中添加了以下内容,进行了虚拟测试:
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..
在我的仪器测试中:
@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()));
}
这个测试成功了,但是我不想在我的活动中使用文本,而是想使用标签或其他东西。