Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating a click on a menu item in Robolectric

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?

like image 897
futlib Avatar asked Sep 23 '11 05:09

futlib


5 Answers

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!

like image 142
lemon Avatar answered Nov 08 '22 21:11

lemon


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()));
like image 36
hidro Avatar answered Nov 08 '22 19:11

hidro


In robolectric 3.0+ the class is called RoboMenuItem

like image 12
karlicoss Avatar answered Nov 08 '22 19:11

karlicoss


You are already using Robolectric then why don't use RoboMenuItem ?

private MenuItem menuItemName = new RoboMenuItem(R.id.action_names);
private MenuItem menuItemStar = new RoboMenuItem(R.id.action_stars);

add as many items as required.

@Test
public void onOptionItemSelectedTest() {
    activity.onOptionsItemSelected(menuItemStar);
    activity.onOptionsItemSelected(menuItemName);
}

Make sure your activity is not null

 @Before
public void setUp() {
    activity = Robolectric.buildActivity(MainActivity.class)
            .create(new Bundle())
            .saveInstanceState(new Bundle())
            .restoreInstanceState(new Bundle())
            .resume()
            .get();
}

Robolectric version 4.3

like image 2
Aks4125 Avatar answered Nov 08 '22 20:11

Aks4125


Using robolectric 2.4:

Activity activity = Robolectric.buildActivity(MainActivity.class).create().get();
MenuItem item = new TestMenuItem(R.id.settings_option_item);
activity.onOptionsItemSelected(item);
like image 1
karma Avatar answered Nov 08 '22 21:11

karma