2011-09-23 152 views
28

这是相当简单的模拟Robolectric点击一个按钮:模拟菜单项上点击在Robolectric

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

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

回答

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

享受!

+13

它已成为更容易,而不是创建匿名类型,您现在可以使用 ''MenuItem item =新的TestMenuItem(R.id.hello);'' – passy

+1

这对目前的robolectric [2012-11]不起作用? – Freewind

+0

它使用@ passy的方式在Robolectric 2.3上工作 – Maragues

1

使用robolectric 2.4:

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

在robolectric 3.0+的类被称为RoboMenuItem

+1

然后呢?我猜你的意思是TestMenuItem成为RoboMenuItem,但其他代码呢? – SJoshi

16

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