[使用FragmentScenario测试片段时如何测试与菜单的交互

问题描述 投票:1回答:1

我正在尝试使用FragmentScenario测试一个片段。该片段具有其自己的菜单。操作栏上有一个添加图标,单击此菜单项将启动一个子片段,用户可以从中添加新项。因此,我正在尝试测试此行为。但是,您可能知道,FragmentScenario将在EmptyFragmentActivity中启动片段,而不启动实际的主机活动。由于操作栏不是片段布局的一部分,而是属于主机活动,因此操作栏和菜单甚至在测试过程中都不可见。那么如何测试与菜单的交互?

我从官方文档中找到了这条信息:

如果需要在片段本身上调用方法,例如响应选项菜单中的选择,您可以安全地通过实现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.
            }
        }
    }
}

但是,如何将正确的项目传递给onOptionsItemSelected回调?我试图将addMenuItem定义为成员变量,并在onCreateOptionsMenu内对其进行初始化,但它返回null。在测试过程中似乎未调用onCreateOptionsMenu。因此,我不知道如何测试用户与菜单的交互。

android menu fragment ui-testing android-fragmentscenario
1个回答
0
投票

我通过嘲笑菜单项解决了这个问题:

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

//Create a mock for the menu item with the desired item id.
val addMenuItem = mock(MenuItem::class.java)
`when`(addMenuItem.itemId).thenReturn(R.id.action_add)

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

它可以工作,但是如果有人有更好/替代的解决方案,我们将很高兴听到。

© www.soinside.com 2019 - 2024. All rights reserved.