简体   繁体   English

如何使用Robolectric在Android中测试菜单

[英]How to test menu in Android with Robolectric

I need to write tests to menu in Android application using Robolectric. 我需要使用Robolectric在Android应用程序中编写测试菜单。

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. 以下示例应该是任何开始使用Robolectric的人的一个很好的例子。 It's using Robolectric 3.0 under AndroidStudio. 它在AndroidStudio下使用Robolectric 3.0。

@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. 实际上,如果可能的话,你应该避免使用避免使用RoboMenuItem。 You can get the actual menu created by the activity by having robolectric create the activity and make it visible. 您可以通过让robolectric创建活动并使其可见来获取活动创建的实际菜单。

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

You can then use a ShadowActivity to get the actually created menu options; 然后,您可以使用ShadowActivity获取实际创建的菜单选项;

shadowOf(activity).getOptionsMenu()

To get the actual MenuItem: 要获取实际的MenuItem:

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

You can then pass that actual menuItem into the onOptionsItemSelected. 然后,您可以将实际的menuItem传递给onOptionsItemSelected。

RoboMenuItem is just a dummy facade and actually it is recommended by the robolectric developers to avoid it if possible. RoboMenuItem只是一个虚拟外观,实际上robolectric开发人员建议尽可能避免使用它。

kingargyle has a good answer on getting the MenuItem. 获得MenuItem时,kingargyle有一个很好的答案。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM