Robolectric でボタンのクリックをシミュレートするのはかなり簡単です。
Button someButton = (Button) findViewById(R.id.some_button);
someButton.performClick();
ただし、メニュー項目で同じことを行う方法がわかりません。でメニューを作成しましたActivity.onCreateOptionsMenu
が、その項目の 1 つのクリックをシミュレートするにはどうすればよいですか?
Robolectric でボタンのクリックをシミュレートするのはかなり簡単です。
Button someButton = (Button) findViewById(R.id.some_button);
someButton.performClick();
ただし、メニュー項目で同じことを行う方法がわかりません。でメニューを作成しましたActivity.onCreateOptionsMenu
が、その項目の 1 つのクリックをシミュレートするにはどうすればよいですか?
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);