简体   繁体   中英

Android espresso test NavigationView

I am writing some espressotests for an appplication I recently made. I'm using a NavigationView inside a DrawerLayout as sliding menu.

I managed to open the drawer this way:

        onView(withId(R.id.drawer_layout)).perform(open());

This works so now I am trying to perform a click on a menuitem in the NavigationView.

onView(withId(R.id.nav_register))..

can not find the view. I tried several things but I can't find a way to retrieve the menuitem view. This is the way the items are assigned in the code:

    <android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

and activity_main_drawer.xml

<group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_home"
        android:icon="@drawable/ic_menu_home"
        android:title="Home" />
    <item
        android:id="@+id/nav_register"
        android:icon="@drawable/ic_menu_register"
        android:title="Registreer" />
    <item
        android:id="@+id/nav_login"
        android:icon="@drawable/ic_menu_login"
        android:title="Log in" />
    <item
        android:id="@+id/nav_play"
        android:icon="@drawable/ic_menu_play"
        android:title="Speel sessie" />
    <item
        android:id="@+id/nav_logout"
        android:icon="@drawable/ic_menu_logout"
        android:title="Log uit" />
</group>

I read something about NavigationViewMenuItem is a private member and not accessible. Can someone help me out?

Greets! Shenno

Actually, the View representing the menu item doesn't know the id of the menu item in Android. As a result the method withId() doesn't work in Espresso with menu items specifically. I suggest you use the withText method:

onView(withText("the item title")).

如果你想坚持使用ID,那么你可以使用:

onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id. nav_register));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM