Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test interactions with menu when testing fragments with FragmentScenario

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.

like image 209
Oya Canli Avatar asked Dec 01 '19 18:12

Oya Canli


1 Answers

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)
 }

EDIT : This solution saved the day at that time. But now I began to prefer to put the toolbar in the fragment layout instead of activity, especially if I have different menus for different fragments, so I that I don't have the same problem in other projects. That's a possible solution as well.

like image 104
Oya Canli Avatar answered Oct 23 '22 21:10

Oya Canli