Android - How to click on an item on a navigation drawer using Espresso?

josmenag picture josmenag · Mar 11, 2016 · Viewed 9.7k times · Source

I am new to Android development. I want to use Espresso to test that my drawer opens, then click on an item and check that it opens a new activity. I've been searching for examples about this but haven't had any luck.

Answer

GVillani82 picture GVillani82 · Mar 11, 2016
@Test
public void clickOnYourNavigationItem_ShowsYourScreen() {
    // Open Drawer to click on navigation.
    onView(withId(R.id.drawer_layout))
        .check(matches(isClosed(Gravity.LEFT))) // Left Drawer should be closed.
        .perform(DrawerActions.open()); // Open Drawer

    // Start the screen of your activity.
    onView(withId(R.id.nav_view))
        .perform(NavigationViewActions.navigateTo(R.id.your_navigation_menu_item));

    // Check that you Activity was opened.
    String expectedNoStatisticsText = InstrumentationRegistry.getTargetContext()
        .getString(R.string.no_item_available);
    onView(withId(R.id.no_statistics)).check(matches(withText(expectedNoStatisticsText)));
}

This does exactly what you are looking for.

Other examples are available here or here