Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Menu

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.

like image 682
cement Avatar asked Jun 21 '10 13:06

cement


People also ask

What are the 6 types of menus?

The five types of menus most commonly used are a la carte menus, static menus, du jour menus, cycle menus, and fixed menus.

What are the 4 considerations in designing the menu?

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.


2 Answers

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:

  1. Clicks the menu option,
  2. Ensures we go to the appropriate activity after the menu option is clicked, and
  3. finishes the activity that was started (very important for the tests following this one).

I hope this helps.

like image 153
Dan Avatar answered Oct 20 '22 02:10

Dan


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.

like image 2
Robby Pond Avatar answered Oct 20 '22 01:10

Robby Pond