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.
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);
}
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With