kotlinjunitandroid-viewandroid-espresso

Click a PopupMenu button with Espresso?


Is there a way to click an item in an inflated PopupMenu anchored to a ListView item?

I have a PopupMenu that is created by clicking a button inside a ListView. I need to click an item inside the popup by id.

Here is my test:

val item = onData(anything()).inAdapterView(withId(R.id.profiles_list)).atPosition(index)
val menuButton = item.onChildView(withId(R.id.options_button))
menuButton.perform(click()) // This opens the popup (anchored to menuButton)

And here is how the menu is created after clicking options_button:

val popup = PopupMenu(context, menuButton)
popup.setOnMenuItemClickListener {
    when (it.itemId) {
        R.id.profile_rename -> {
            // Action to perform
            true
        }
        else -> false
    }
}
popup.menuInflater.inflate(R.menu.list_item_profile, popup.menu)
popup.show()

I've tried using isPlatformPopup, which does not find the popup:

menuButton.inRoot(isPlatformPopup()).onChildView(withId(R.id.profile_rename)).perform(click())

Solution

  • Found that the item could be retrieved using withText(), rather than with onChildView(withId())

    onView(withText(R.string.rename)).inRoot(isPlatformPopup()).perform(click())
    

    Based on the solution from Verify items in a popup menu with espresso