How to test menus in Android using Robolectric

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

Menu Source Code:

@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 write tests

+3
source share
2 answers

The following example should be a good example for those who start working with Robolectric. It uses 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());
    }
}
+6
source

In fact, you should not avoid using RoboMenuItem, if possible. You can get the actual menu created by the activity using robolectric, which creates the action and makes it visible.

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

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

shadowOf(activity).getOptionsMenu()

To get the actual MenuItem:

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

onOptionsItemSelected.

RoboMenuItem - , , , robolectric , .

+2

All Articles