Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 563
josmenag Avatar asked Mar 11 '16 16:03

josmenag


People also ask

How do you scroll to element in espresso?

You can use SWIPE to scroll to the bottom of the screen: Espresso. onView(ViewMatchers. withId(R.

Why do we use the navigation drawer in Android app?

Navigation drawers provide access to destinations and app functionality, such as switching accounts. They can either be permanently on-screen or controlled by a navigation menu icon. Navigation drawers are recommended for: Apps with five or more top-level destinations.


2 Answers

@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

like image 96
GVillani82 Avatar answered Sep 27 '22 17:09

GVillani82


Incase someone else lands to this question and he/she is using kotlin you can add extension function on ActivityScenario class to grab drawer icon or back button

For more description check this GOOGLE-TESTING-CODELAB-8

fun <T: Activity> ActivityScenario<T>.getToolbarNavigationContentDescriptor(): String {
    var description = ""
    onActivity {
        description = it.findViewById<Toolbar>(R.id.toolbar).navigationContentDescription as String
    }
    return description
}

On your tests, you can do something like this

// Check drawer is closed
onView(withId(R.id.drawer_layout)).check(matches(isClosed(Gravity.START)))

// Click drawer icon
onView(
    withContentDescription(
        scenario.getToolbarNavigationContentDescriptor()
    )
).perform(click())

// Check if drawer is open
onView(withId(R.id.drawer_layout)).check(matches(isOpen(Gravity.START)))

Happy coding . . .

like image 28
Emmanuel Mtali Avatar answered Sep 27 '22 18:09

Emmanuel Mtali