2011-09-23 391 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()));