Search code examples
androidandroid-espressonavigationviewandroid-navigationview

How to test if a NavigationView menu item is disabled or enabled with Espresso?


I have a NavigationView with a menu where some menu items should be disabled when a user is not logged in:

private void setupNavigationViewMenu(boolean isUserLoggedIn) {
    Menu menu = mNavigationView.getMenu();
    menu.findItem(R.id.item_charge_cards).setEnabled(isUserLoggedIn);
    menu.findItem(R.id.item_charge_sessions).setEnabled(isUserLoggedIn);
    menu.findItem(R.id.item_invoices).setEnabled(isUserLoggedIn);
}

I want to create an Espresso test, which will assert that the menu items are really disabled.

I have written the following test, but it's failing:

@Test
public void navigationMenuItems_AreDisabled() {
    openNavigationDrawer();
    onView(getNavigationItemWithString(R.string.navigation_view_item_charging_cards))
            .check(matches(not(isEnabled())));
    onView(getNavigationItemWithString(R.string.navigation_view_item_charging_sessions))
            .check(matches(not(isEnabled())));
    onView(getNavigationItemWithString(R.string.navigation_view_item_invoices))
            .check(matches(not(isEnabled())));
}

public static Matcher<View> getNavigationItemWithString(String string) {
    return allOf(isAssignableFrom(AppCompatCheckedTextView.class), withText(string));
}

The stacktrace:

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'not is enabled' doesn't match the selected view.
Expected: not is enabled
Got: "AppCompatCheckedTextView{id=2131624121, res-name=design_menu_item_text, visibility=VISIBLE, width=651, height=126, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=42.0, y=0.0, text=Laadpassen, input-type=0, ime-target=false, has-links=false, is-checked=false}"
...

Do you have any suggestions how to write the correct test?


Solution

  • A NavigationView menu item is not a single view, but a ViewGroup, so the enabled status is applied to NavigationMenuItemView, not AppCompatCheckedTextView. In order to fix your test, you must use the following Matcher to find the correct layout in the view hierarchy:

    public static Matcher<View> getNavigationItemWithString(String string) {
        Matcher<View> childMatcher = allOf(isAssignableFrom(AppCompatCheckedTextView.class), withText(string));
        return allOf(isAssignableFrom(NavigationMenuItemView.class), withChild(childMatcher));
    }