Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 564
Hicy Avatar asked Mar 19 '16 19:03

Hicy


2 Answers

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")).
like image 105
Coralie B Avatar answered Oct 14 '22 17:10

Coralie B


If you want to stick to ID then you can use :

onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id. nav_register));
like image 38
priyanka p Avatar answered Oct 14 '22 16:10

priyanka p