1

I am currently learning Robolectric to test for Android and I am having trouble obtaining my application's menu. Right now, Robolectric's getOptionsMenu() is returning null. The code itself works fine but the test always returns null for the options menu.

My code is the following

@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");
}

Does anyone know why Robolectric is returning null? Did I miss any dependencies?

Marco Poloe
  • 269
  • 5
  • 13

1 Answers1

3

The onCreateOptionsMenu will be called after oncreate so to make sure that you can see your menu try

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

or you can make sure the activity is visible

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

From docs

What’s This visible() Nonsense?

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?

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68