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

Viewed 11821

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.

2 Answers

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 . . .

Related