Simulating a click on a menu item in Robolectric

In robolectric 3.0+ the class is called RoboMenuItem


MenuItem item = new TestMenuItem() {
  public int getItemId() {
    return R.id.hello;
  }
};

activity.onOptionsItemSelected(item);

ShadowActivity shadowActivity = Robolectric.shadowOf(activity);
Intent startedIntent = shadowActivity.getNextStartedActivity();
ShadowIntent shadowIntent = Robolectric.shadowOf(startedIntent);

assertThat(shadowIntent.getComponent().getClassName(), equalTo(HelloActivity_.class.getName()));

Enjoy!


In Robolectric 3.0+, you can use ShadowActivity.clickMenuItem(menuItemResId):

        // Get shadow
    ShadowActivity shadowActivity = Shadows.shadowOf(activity);

    // Click menu
    shadowActivity.clickMenuItem(R.id.settings_option_item);

    // Get intent
    Intent startedIntent = shadowActivity.getNextStartedActivity();
    ShadowIntent shadowIntent = Shadows.shadowOf(startedIntent);

// Make your assertion
assertThat(shadowIntent.getComponent().getClassName(), equalTo(HelloActivity_.class.getName()));