currently to click on menu-item that is sometimes on some devices in the overflow-menu I am doing the following:
fun invokeMenu(@IdRes menuId: Int, @StringRes menuStringRes: Int) {
try {
onView(withId(menuId)).perform(click())
} catch (nmv: NoMatchingViewException) {
openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getInstrumentation().targetContext)
onView(withText(menuStringRes)).perform(click())
}
}
But I am searching for a better approach - ideally something where I just have to know the menu-id. How do you do this in your espresso tests?
Unfortunately, your ideal case cannot be acomplished. This is due to the construction of support libraries.
Let's start from
PopupMenu
, which has a reference toMenuPopupHelper
, which has reference toMenuPopup
. This is an abstract class extended ie. byStandardMenuPopup
. It has reference toMenuAdapter
. If you look into the line 92 ofMenuAdapter
you will see, the line:This is the key method invocation. It can be invoked either in
ActionMenuItemView
orListMenuItemView
. Their implementations differ in the case, that id is attached to ActionMenuItemView, and is not attached to ListMenuItemViewMoreover,
MenuAdapter.getItemId(int position)
returns justposition
. The id of menu item is lost in overflow menu.Hovewer, your code can be simplified to one liner. Define a function:
Usage: