我有一个带有查看寻呼机的标签布局。我正在使用 Espresso 来测试我的Android应用。在我之前的项目中,我使用选项卡标题执行单击以选择选项卡位置,如下所示。
Espresso.onView(ViewMatchers.withText("MAP"))
.perform(ViewActions.click());
现在我有114个标签。因此,我无法使用上述方法随机选择这些标签进行测试。有什么方法可以根据它的位置选择标签。我已经检查了其他解决方案,但没有一个帮助我。
答案 0 :(得分:6)
应该可以使用自定义ViewAction
。像这样:
fun selectTabAtPosition(tabIndex: Int): ViewAction {
return object : ViewAction {
override fun getDescription() = "with tab at index $tabIndex"
override fun getConstraints() = allOf(isDisplayed(), isAssignableFrom(TabLayout::class.java))
override fun perform(uiController: UiController, view: View) {
val tabLayout = view as TabLayout
val tabAtIndex: TabLayout.Tab = tabLayout.getTabAt(tabIndex)
?: throw PerformException.Builder()
.withCause(Throwable("No tab at index $tabIndex"))
.build()
tabAtIndex.select()
}
}
}
和用法:
onView(withId(R.id.tab_layout)).perform(selectTabAtPosition(99))
答案 1 :(得分:1)
作为未使用过Kotlin的人,这就是Java语言。它与@Be_Negative基本相同,因此只需以相同的方式使用它即可。
@NonNull
private static ViewAction selectTabAtPosition(final int position) {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return allOf(isDisplayed(), isAssignableFrom(TabLayout.class));
}
@Override
public String getDescription() {
return "with tab at index" + String.valueOf(position);
}
@Override
public void perform(UiController uiController, View view) {
if (view instanceof TabLayout) {
TabLayout tabLayout = (TabLayout) view;
TabLayout.Tab tab = tabLayout.getTabAt(position);
if (tab != null) {
tab.select();
}
}
}
};
}
答案 2 :(得分:1)
以上两个答案都很好。对我来说,选择标签后,我还想通过与标题匹配来确认它是正确的标签。由于这篇文章是关于浓缩咖啡测试的,因此我将在此处分享代码段,因为这可能对某人有所帮助。
fun matchCurrentTabTitle(tabTitle: String): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description?) {
description?.appendText("unable to match title of current selected tab with $tabTitle")
}
override fun matchesSafely(item: View?): Boolean {
val tabLayout = item as TabLayout
val tabAtIndex: TabLayout.Tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)
?: throw PerformException.Builder()
.withCause(Throwable("No tab at index ${tabLayout.selectedTabPosition}"))
.build()
return tabAtIndex.text.toString().contains(tabTitle, true)
}
}
}
fun matchTabTitleAtPosition(tabTitle: String, tabIndex: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description?) {
description?.appendText("unable to select tab at index $tabIndex and match title with $tabTitle")
}
override fun matchesSafely(item: View?): Boolean {
val tabLayout = item as TabLayout
val tabAtIndex: TabLayout.Tab = tabLayout.getTabAt(tabIndex)
?: throw PerformException.Builder()
.withCause(Throwable("No tab at index $tabIndex"))
.build()
return tabAtIndex.text.toString().contains(tabTitle, true)
}
}
}