Select an item in the NavigationView with espresso
I have this piece of code
private void setupDrawerLayout() {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
final int itemId = menuItem.getItemId();
switch (itemId) {
case R.id.drawer_my_mixes:
replaceFragment(MyMixesFragment.newInstance());
drawerLayout.closeDrawers();
break;
and so on...
I want espresso to click R.id.drawer_settings
, which will basically open a snippet called SettingsFragment. How should I do it? I have tried this without success
private ViewInteraction navigateToSettings(){
openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
return onView(withText("Settings")).perform(click());
}
source to share
The correct way is to use the onData function for Espresso.
onData(allOf(is(instanceOf(NavigationMenuItem.class)), ... )).perform(click());
But NavigationMenuItem is not available as it is a private nested class.
The problem is waiting for https://code.google.com/p/android/issues/detail?id=187701 to find a solution on it. Go add a star to it; -)
source to share
openActionBarOverflowOrOptionsMenu () does not open navigation.
For me the following works:
//Open NavigationView
Matcher<View> isImageButton = withClassName(is(ImageButton.class.getName()));
Matcher<View> isInToolbar = isDescendantOfA(withId(R.id.toolbar));
onView(allOf(isInToolbar, isImageButton)).perform(click());
//Click on item in NavigationView
onView(withText(R.string.logout)).perform(click());
This solution works for me temporarily until a better solution is found, such as the one suggested by user40797 ...
source to share