I need to cover Menu functionality by unit tests, however I'm struggling to obtain Menu object.
Following test case fails (mMenu is null):
sendKeys(KeyEvent.KEYCODE_MENU);
mMenu = (Menu) mActivity.findViewById(com.###.###.R.id.main_menu);
assertNotNull(mMenu);
Please advice. Thank you.
The five types of menus most commonly used are a la carte menus, static menus, du jour menus, cycle menus, and fixed menus.
By getting the menu right, in tone, language, design and appeal, it can be the key component in the decision-making process and can be the reason someone tries your offer or decides not to.
I ran into this same scenario and came up with the following (very simple) solution in my implementation of ActivityInstrumentationTestCase:
...
ActivityMonitor am = getInstrumentation().addMonitor(LoginActivity.class.getName(), null, false);
// Click the menu option
getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
getInstrumentation().invokeMenuActionSync(mActivity, R.id.logout, 0);
Activity a = getInstrumentation().waitForMonitorWithTimeout(am, 1000);
assertEquals(true, getInstrumentation().checkMonitorHit(am, 1));
a.finish();
...
This snippet of code does three things:
I hope this helps.
What exactly are you trying to test? That menu items do the correct action?
You can call Activity.openOptionsMenu() to open the menu and get a reference to the menu by overriding one of the onMenu methods. At that point you can use Menu.performIdentifierAction to select menu items.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With