在Robolectric中模拟button点击相当简单:
Button someButton = (Button) findViewById(R.id.some_button); someButton.performClick();
但是,我似乎无法弄清楚如何做一个菜单项相同的事情。 我在Activity.onCreateOptionsMenu
创build一个菜单,我怎样才能模拟点击其中的一个项目?
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()));
请享用!
在Robolectric 3.0+中,您可以使用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()));
在robolectric 3.0+中,这个类被称为RoboMenuItem
使用robolectric 2.4:
Activity activity = Robolectric.buildActivity(MainActivity.class).create().get(); MenuItem item = new TestMenuItem(R.id.settings_option_item); activity.onOptionsItemSelected(item);