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.
Asked
Active
Viewed 1.2k times
2 Answers
49
@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.

Sneh Pandya
- 8,197
- 7
- 35
- 50

GVillani82
- 17,196
- 30
- 105
- 172
-
Looks like the source code link for `navigateTo` in custom ViewAction is broken. – Sudarsan GP Feb 12 '17 at 14:31
-
@SudarsanGP you are right. It seems that it has been added to the android sdk. I am going to update the reference in the answer. Just use `NavigationViewActions` defined in `android.support.test.espresso.contrib` – GVillani82 Feb 12 '17 at 14:58
-
From where did you get the `DrawerActions` class? Please add the import statements. – Roshana Pitigala May 26 '20 at 17:37
-
It is easy to find @RoshanaPitigala in the [official android dev page](https://developer.android.com/reference/androidx/test/espresso/contrib/DrawerActions) – GVillani82 May 26 '20 at 20:09
2
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 . . .

Emmanuel Mtali
- 4,383
- 3
- 27
- 53