当导航抽屉包含带有图像和文本视图的行列表时,如何单击导航抽屉项?
我使用了以下的Espresso测试源示例:git / testapp_test / src / main / java / com / google / android / apps / common / testing / ui / testapp / DrawerActionsTest.java
我从贡献中检索了DrawerActions和DrawerMatchers,并将它们放在我的测试项目中。
导航抽屉行为:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="@drawable/list_selector">
<ImageView
android:id="@+id/icon"
etc ... />
<TextView
android:id="@+id/title"
etc.... />
</RelativeLayout>
导航项目是:
public class NavDrawerItem {
public String title;
public int icon;
....
// a matcher
@Override
public boolean equals( Object mob2) {
String otherName = ((NavDrawerItem) mob2).title;
return( title.equals( otherName));
}
}
NavigationDrawerAdapter填充导航抽屉视图。
Espresso测试源打开抽屉,关闭它,重新打开它......但我找不到第一个“导入”项目的匹配项。因此,测试会在执行点击时停止。
代码是:
public LearnerAppAutoTest() {
super(MainActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
getActivity();
}
public void testOpenAndCloseDrawer() {
openDrawer(R.id.drawer_layout);
closeDrawer(R.id.drawer_layout);
openDrawer(R.id.drawer_layout);
onView(withId(R.id.drawer_layout)).check(matches(isOpen()));
String rowContents = "Import";
// Option 1: too many lists having an "Import" string
onData( allOf( is( instanceOf( String.class)), is( rowContents))).perform(click());
// Option 2: selecting on NavDrawerItem.class and a matcher
// ... still all matches, also in other lists match. Why? They don't have NavDrawerItems.
onData( allOf( is( instanceOf( NavDrawerItem.class)), is( rowContents))).perform(click());
// Option 3: custom matcher
// ... still all matches, also in other lists match. Why?
onData( allOf( instanceOf( NavDrawerItem.class), navDrawerItemHavingName( rowContents))).perform( click());
}
所以,无论我编程什么,都有多个匹配器......甚至来自没有NavDrawerItem类的列表。
答案 0 :(得分:8)
试试这个:
Espresso.onView(Matchers.allOf(ViewMatchers.withId(R.id.drawerItemNameTextView), ViewMatchers.hasSibling(ViewMatchers.withText(((NavDrawerItem)item).getItemName())))).perform(ViewActions.click());