I would like to assert the visibility of menu items. However, my menu items always returns true. I am using the following code to inflate my menu.
SherlockMenuInflater inflater = new SherlockMenuInflater(activity);
MenuBuilder menu = new MenuBuilder(activity);
fragment.onCreateOptionsMenu(menu, inflater);
System.out.println(menu.findItem(R.id.submit).isVisible() + " " + menu.findItem(R.id.next).isVisible() + " "
+ menu.findItem(R.id.done).isVisible());
assertEquals(3, menu.size());
assertFalse(menu.findItem(R.id.submit).isVisible());
assertTrue(menu.findItem(R.id.next).isVisible());
assertFalse(menu.findItem(R.id.done).isVisible());
Am I doing something wrong?
My OptionsMenu
has two MenuItem
s, which on of them (Sort
) has its own subMenu
with two items.
Here's my Robolectric
test code for OptionsMenu
visibility:
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class MainActivityTest {
private static MainActivity mActivity;
@Before
public void setMainActivity() {
if (mActivity == null) {
mActivity = Robolectric.buildActivity(MainActivity.class).create().visible().get();
}
}
@Test
public void checkMainActivityOptionsMenuValues() throws Exception {
//get MainActivity.toolbar instance
Toolbar toolbar = ButterKnife.findById(mActivity, R.id.toolbar);
//get ShadowActivity instance
ShadowActivity shadowActivity = shadowOf(mActivity);
//call onCreateOptionsMenu using toolbar.menu
shadowActivity.onCreateOptionsMenu(toolbar.getMenu());
//assert that OptionsMenu has visible items
assertTrue(shadowActivity.getOptionsMenu().hasVisibleItems());
//assert that `Settings` MenuItem is visible
assertEquals(shadowActivity.getOptionsMenu().findItem(R.id.action_settings).isVisible(), true);
//assert that `Sort` MenuItem is visible
assertEquals(shadowActivity.getOptionsMenu().getItem(0).getTitle(),
mActivity.getString(R.string.action_sort));
//assert that `Sort` has subMenu with `By Value id` value
assertEquals(shadowActivity.getOptionsMenu().getItem(0).getSubMenu().getItem(0).getTitle(),
mActivity.getString(R.string.menu_sort_a_z));
//assert that `Sort` has subMenu with `By Joke Length` value
assertEquals(shadowActivity.getOptionsMenu().getItem(0).getSubMenu().getItem(1).getTitle(),
mActivity.getString(R.string.menu_sort_size));
}
}
If you don't use Butterknife
, instead of line:
Toolbar toolbar = ButterKnife.findById(mActivity, R.id.toolbar);
use
Toolbar toolbar = mActivity.findViewById(R.id.toolbar);
I'm using Robolectric 3.1.
Hope it would help
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