模拟Robolectric中菜单项的单击

fut*_*lib 29 android robolectric

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

Button someButton = (Button) findViewById(R.id.some_button);
someButton.performClick();
Run Code Online (Sandbox Code Playgroud)

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

lem*_*mon 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()));
Run Code Online (Sandbox Code Playgroud)

请享用!

  • 它变得更加容易,而不是创建匿名类型,你现在可以使用``MenuItem item = new TestMenuItem(R.id.hello);`` (14认同)
  • 确保在Robolectric 3.0+中使用`RoboMenuItem(id)`. (10认同)

hid*_*dro 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()));
Run Code Online (Sandbox Code Playgroud)


kar*_*oss 9

在robolectric 3.0+中,该类被称为 RoboMenuItem

  • 然后什么?我猜你的意思是TestMenuItem变成了RoboMenuItem,但是其余的代码呢? (2认同)