Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test ActionMenuItemView's icon in Espresso

I have a button in action bar, for which the icon is changed depending of a boolean. I would like to check which drawable resource is used.

Here is the code where the icon is changed:

@Override
public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    MenuItem item = menu.findItem(R.id.menu_favorite);
    if(mIsFavorite)
        item.setIcon(R.drawable.ab_icon_on);
    else
        item.setIcon(R.drawable.ab_icon_off);
}

When icon needs to be changed, the menu is invalidated:

// request menu update
supportInvalidateOptionsMenu();

Finally, my espresso code where I would like to check the result:

@Test
public void action_setUnsetFavorite() {
    // check favorite off
    onView(withImageDrawable(R.drawable.ab_icon_off))
            .check(matches(isDisplayed()));

    // click favorite button
    onView(withId(R.id.menu_favorite))
            .perform(click());

    // check favorite on
    onView(withImageDrawable(R.drawable.ab_icon_on))
            .check(matches(isDisplayed()));

Please note that I am using a custom matcher found here.

like image 246
Rémi F Avatar asked Dec 02 '15 22:12

Rémi F


1 Answers

I'm not a 100% sure on how the matchers work and whether this is the best response but using a slightly different version of the method certainly works.

The problem is that the current matcher only works with ImageViews. ActionMenuItemView actually subclasses textView so won't match and it also has no method for getDrawable().

Please note, this still requires the sameBitmap method from the original post.

public static Matcher<View> withActionIconDrawable(@DrawableRes final int resourceId) {
    return new BoundedMatcher<View, ActionMenuItemView>(ActionMenuItemView.class) {
        @Override
        public void describeTo(final Description description) {
            description.appendText("has image drawable resource " + resourceId);
        }

        @Override
        public boolean matchesSafely(final ActionMenuItemView actionMenuItemView) {
            return sameBitmap(actionMenuItemView.getContext(), actionMenuItemView.getItemData().getIcon(), resourceId);
        }
    };
}
like image 146
Barry Irvine Avatar answered Oct 16 '22 12:10

Barry Irvine