这是相当简单的模拟Robolectric点击一个按钮:模拟菜单项上点击在Robolectric
Button someButton = (Button) findViewById(R.id.some_button);
someButton.performClick();
不过,我似乎无法弄清楚如何做同样的事情与菜单项。我在Activity.onCreateOptionsMenu
中创建了一个菜单,我如何模拟点击其中一个项目?
这是相当简单的模拟Robolectric点击一个按钮:模拟菜单项上点击在Robolectric
Button someButton = (Button) findViewById(R.id.some_button);
someButton.performClick();
不过,我似乎无法弄清楚如何做同样的事情与菜单项。我在Activity.onCreateOptionsMenu
中创建了一个菜单,我如何模拟点击其中一个项目?
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 2.4:
Activity activity = Robolectric.buildActivity(MainActivity.class).create().get();
MenuItem item = new TestMenuItem(R.id.settings_option_item);
activity.onOptionsItemSelected(item);
在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()));
它已成为更容易,而不是创建匿名类型,您现在可以使用 ''MenuItem item =新的TestMenuItem(R.id.hello);'' – passy
这对目前的robolectric [2012-11]不起作用? – Freewind
它使用@ passy的方式在Robolectric 2.3上工作 – Maragues