android – How to test interactions with menu when testing fragments with FragmentScenario-ThrowExceptions

Exception or error:

I’m trying to test a fragment using FragmentScenario. This fragment has its own menu. There is an add icon on the action bar and clicking on this menu item launches a child fragment from which user can add new items. So I’m trying to test this behavior.
However, as you may know, FragmentScenario launches the fragment within an EmptyFragmentActivity, without launching the real host activity. As action bar is not a part of the fragment layout but belongs to the host activity, action bar and thus menu doesn’t even become visible during testing. So how can I test interactions with the menu?

I found this piece of information from the official docs:

If you need to call a method on the fragment itself, such as
responding to a selection in the options menu, you can do so safely by
implementing FragmentAction:

@RunWith(AndroidJUnit4::class)
class MyTestSuite {
    @Test fun testEventFragment() {
        val scenario = launchFragmentInContainer<MyFragment>()
        scenario.onFragment(fragment ->
            fragment.onOptionsItemSelected(clickedItem) {
                //Update fragment's state based on selected item.
            }
        }
    }
}

However, how to pass the correct item to the onOptionsItemSelected callback? I tried to define addMenuItem as a member variable and initialize it inside onCreateOptionsMenu, but it returns null. onCreateOptionsMenu does not seem to be called during testing. So I don’t know how to test user interactions with the menu.

How to solve:

I solved the issue by passing a dummy menu item:

val scenario = launchFragmentInContainer<CategoryListFragment>(Bundle(), R.style.AppTheme)

//Create a dummy menu item with the desired item id.
val context: Context = ApplicationProvider.getApplicationContext<AndroidTestApplication>()
val addMenuItem = ActionMenuItem(context, 0, R.id.action_add, 0, 0, null)

 //Call onOptionsItemSelected with the dummy menu item
 scenario.onFragment { fragment ->
       fragment.onOptionsItemSelected(addMenuItem)
 }

It works but if anyone has a better/alternative solution, would be happy to hear.

Leave a Reply

Your email address will not be published. Required fields are marked *