質問

I need to write tests to menu in Android application using Robolectric.

Source code of menu:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    switch (item.getItemId()) {
    case R.id.exit:
        this.finish();
        break;
    default:
        Toast.makeText(this, getString(R.string.errMsg), Toast.LENGTH_SHORT).show();
        break;
    }
    return super.onMenuItemSelected(featureId, item);
} 

Please help to write tests

役に立ちましたか?

解決

The following example should be a good example for anyone who is getting started with Robolectric. It's using Robolectric 3.0 under AndroidStudio.

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 19)
public class MainActivityTest {
    @Test
    public void shouldCloseActivity() {
        MainActivity activity = Robolectric.setupActivity(MainActivity.class);
        MenuItem menuItem = new RoboMenuItem(R.id.exit);
        activity.onOptionsItemSelected(menuItem);
        ShadowActivity shadowActivity = Shadows.shadowOf(activity);
        assertTrue(shadowActivity.isFinishing());
    }
}

他のヒント

Actually you should avoid using avoid using RoboMenuItem if possible. You can get the actual menu created by the activity by having robolectric create the activity and make it visible.

MainActivity activity = Robolectric.buildActivity(MainActivity.class).create().visible().get();

You can then use a ShadowActivity to get the actually created menu options;

shadowOf(activity).getOptionsMenu()

To get the actual MenuItem:

shadowOf(activity).getOptionsMenu().findMenuItem(...)

You can then pass that actual menuItem into the onOptionsItemSelected.

RoboMenuItem is just a dummy facade and actually it is recommended by the robolectric developers to avoid it if possible.

kingargyle has a good answer on getting the MenuItem.

If you just want to be able to click on the item however, you can just use:

shadowOf(activity).clickMenuItem(R.id....);

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top