使用 Robolectric 测试菜单

Testing Menu with Robolectric

我目前正在学习 Robolectric 来测试 Android,但我在获取我的应用程序菜单时遇到了问题。 现在,Robolectric 的 getOptionsMenu() 正在返回 null。代码本身工作正常,但选项菜单的测试总是 returns 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?我是否遗漏了任何依赖项?

onCreateOptionsMenu 将在 oncreate 之后调用,因此要确保您可以看到菜单,请尝试

Robolectric.buildActivity(DetailActivity.class, intent).create().resume().get();

或者您可以确保 activity 可见

Robolectric.buildActivity(DetailActivity.class, intent).create().visible().get();

From docs

这是什么 visible() 废话?

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 (amongst other unexpected behavior). The Activity’s hierarchy is attached to the Window on a device or emulator after onPostResume() on the Activity. Rather than make assumptions about when the visibility should be updated, Robolectric puts the power in the developer’s hands when writing tests.

So when do you call it? 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?