Verify items in a popup menu with espresso

2019-06-22 16:33发布

问题:

I have a popupmenu. Uix screenshot provided. Now I want to verify some items in the list by clicking them and verify what's happening.

But no matter what I do I don't seem to be able to select items in the popup menu. The menu does not have an id and I don't think it's possible to set an id of a menu.

I've tried different things like:

onView(nthChildOf(anyOf(withId(android.R.id.title)), 1)).perform(click());

onView(withText("5 sekunder")).perform(click());

But nothing works. How do I click on an item in a popup menu? Here you can find the UIX file with the view hierarachy of the popup menu.

EDIT:

To be clearer when this happens it is when you click on the dots in the right corner of the action bar to expand the submenu. The submenu in my case always consists of three items. The most closest I've come to a solution is:

onData(anything()).atPosition(2).perform(click());

But most of the times it opens the first item and not the item in position two which results in

No activities in stage RESUMED. Did you forget to launch the activity. (test.getActivity() or similar)?

The log can be found here. In the log you can see that it actually clicks the wrong item, it clicks "clicked menu: Menu 1".

回答1:

Espresso provides RootMatchers for that case. It works well for me:

onView(withText("Text")).inRoot(isPopupWindow()).perform(click());

public static Matcher<Root> isPopupWindow() {
        return isPlatformPopup();
}

isPlatformPopup() is an Espresso RootMatcher. You can read more here https://google.github.io/android-testing-support-library/docs/espresso/advanced/#using-inroot-to-target-non-default-windows

Or try this:

onView(withText("Text"))
  .inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView()))))
  .perform(click());


回答2:

Can you try out the following code snippet?

  openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());

  // Click the item.
  onView(withText("Menu1"))
    .perform(click());