Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Espresso - click on navigation drawer item with image and text

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.

like image 885
tm1701 Avatar asked Jan 10 '23 12:01

tm1701


1 Answers

Try this:

Espresso.onView(Matchers.allOf(ViewMatchers.withId(R.id.drawerItemNameTextView), ViewMatchers.hasSibling(ViewMatchers.withText(((NavDrawerItem)item).getItemName())))).perform(ViewActions.click());
like image 174
Aleksandr Gorshkov Avatar answered Feb 20 '23 18:02

Aleksandr Gorshkov