Android Espresso - click on navigation drawer item

2019-03-21 14:20发布

How can I click on a navigation drawer item when the navigation drawer consists of a list of rows with an image and a textview?

I used the Espresso test source example from: git/ testapp_test/ src/ main/ java/ com/ google/ android/ apps/ common/ testing/ ui/ testapp/ DrawerActionsTest.java

I retrieved the DrawerActions and DrawerMatchers from the contribution and put them locally in my test project.

The navigation drawer row is:

<?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>

The navigation items are:

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));
    }
} 

A NavigationDrawerAdapter populates the navigation drawer view.

The Espresso test source opens the drawer, closes it, re-opens it ... but I cannot find a match for the first "Import" item. So the test stops on the perform click.

The code is:

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());

  }

So, whatever I program, there are multiple matchers ... even from lists that don't have NavDrawerItem classes.

1条回答
我命由我不由天
2楼-- · 2019-03-21 15:11

Try this:

Espresso.onView(Matchers.allOf(ViewMatchers.withId(R.id.drawerItemNameTextView), ViewMatchers.hasSibling(ViewMatchers.withText(((NavDrawerItem)item).getItemName())))).perform(ViewActions.click());
查看更多
登录 后发表回答