Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test menu in Android with Robolectric

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

like image 901
lazexe Avatar asked Feb 18 '14 13:02

lazexe


1 Answers

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());
    }
}
like image 144
Xi Wei Avatar answered Oct 04 '22 02:10

Xi Wei