Simulating a click on a menu item in Robolectric

futlib picture futlib · Sep 23, 2011 · Viewed 10.3k times · Source

It's fairly simple to simulate a button click in Robolectric:

Button someButton = (Button) findViewById(R.id.some_button);
someButton.performClick();

However, I can't seem to figure out how to do the same thing with a menu item. I create a menu in Activity.onCreateOptionsMenu, how can I simulate a click on one of its items?

Answer

lemon picture lemon · Dec 21, 2011
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!