模拟Robolectric中菜单项的单击

时间:2011-09-23 05:24:11

标签: android robolectric

在Robolectric中模拟按钮点击非常简单:

Button someButton = (Button) findViewById(R.id.some_button);
someButton.performClick();

然而,我似乎无法弄清楚如何用菜单项做同样的事情。我在Activity.onCreateOptionsMenu创建了一个菜单,如何模拟其中一个项目的点击?

6 个答案:

答案 0 :(得分:29)

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()));

享受!

答案 1 :(得分:17)

在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()));

答案 2 :(得分:9)

在robolectric 3.0+中,该类称为RoboMenuItem

答案 3 :(得分:1)

使用robolectric 2.4:

Activity activity = Robolectric.buildActivity(MainActivity.class).create().get();
MenuItem item = new TestMenuItem(R.id.settings_option_item);
activity.onOptionsItemSelected(item);

答案 4 :(得分:0)

如果您想减少所需的覆盖/抽象编码量,也可以使用Mockito。像这样(在Kotlin中):

val menuItem = mock(MenuItem::class.java)
`when`(menuItem.itemId).thenReturn(R.id.itemId)
activity.onOptionsItemSelected(menuItem)

答案 5 :(得分:0)

您已经在使用Robolectric,那么为什么不使用RoboMenuItem

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

根据需要添加尽可能多的项目。

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

确保您的活动不为空

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

机器人版本4.3