模擬Robolectric中菜單項的單擊

[英]Simulating a click on a menu item in Robolectric


It's fairly simple to simulate a button click in Robolectric:

在Robolectric中模擬按鈕單擊非常簡單:

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

However, I can't seem to figure out how to do the same thing with a menu item. I create a menu in Activity.onCreateOptionsMenu, how can I simulate a click on one of its items?

但是,我似乎無法弄清楚如何用菜單項做同樣的事情。我在Activity.onCreateOptionsMenu中創建了一個菜單,如何模擬其中一個項目的點擊?

5 个解决方案

#1


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

Enjoy!

#2


17  

In Robolectric 3.0+, you can use ShadowActivity.clickMenuItem(menuItemResId):

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

#3


9  

In robolectric 3.0+ the class is called RoboMenuItem

在robolectric 3.0+中,該類稱為RoboMenuItem

#4


1  

Using robolectric 2.4:

使用robolectric 2.4:

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

#5


0  

You can also use Mockito if you'd like to cut down on the amount of overriding/abstract coding required. Like this (in Kotlin):

如果您想減少所需的覆蓋/抽象編碼量,也可以使用Mockito。像這樣(在Kotlin):

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/09/23/72a007eb175bde91d371409063479d4b.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com