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?
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()));
In robolectric 3.0+ the class is called RoboMenuItem
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
Using robolectric 2.4:
Activity activity = Robolectric.buildActivity(MainActivity.class).create().get();
MenuItem item = new TestMenuItem(R.id.settings_option_item);
activity.onOptionsItemSelected(item);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With