我目前正在学习Robolectric来测试Android,但我无法获取应用程序的菜单。
现在,Robolectric的getOptionsMenu()
正在返回null。代码本身工作正常,但测试总是为选项菜单返回null。
我的代码如下
@Test
public void onCreateShouldInflateTheMenu() {
Intent intent = new Intent();
intent.setData(Uri.EMPTY);
DetailActivity dActivity = Robolectric.buildActivity(DetailActivity.class, intent).create().get();
Menu menu = Shadows.shadowOf(dActivity).getOptionsMenu(); // menu is null
MenuItem item = menu.findItem(R.id.action_settings); // I get a nullPointer exception here
assertEquals(menu.findItem(R.id.action_settings).getTitle().toString(), "Settings");
}
有谁知道为什么Robolectric返回null?我错过了任何依赖吗?
答案 0 :(得分:3)
onCreateOptionsMenu
将在oncreate
之后调用,以确保您可以看到您的菜单
Robolectric.buildActivity(DetailActivity.class, intent).create().resume().get();
或者您可以确保活动可见
Robolectric.buildActivity(DetailActivity.class, intent).create().visible().get();
什么是可见的()废话?
Turns out that in a real Android app, the view hierarchy of an Activity is not attached to the Window until sometime after onCreate() is called. Until this happens, the Activity’s views do not report as visible. This means you can’t click on them
(其他意想不到的 行为)。活动的层次结构附加到窗口上 在Activity上的onPostResume()之后的设备或模拟器。而不是 假设何时应该更新可见性, Robolectric在写作时将力量放在开发人员手中 测试所以你什么时候打电话给它?
Whenever you’re interacting with the views inside the Activity. Methods like Robolectric.clickOn() require that the view is visible and properly attached in order to function. You should call visible() after create()
。
Android: When is onCreateOptionsMenu called during Activity lifecycle?