繁体   English   中英

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

[英]How to test interactions with menu when testing fragments with FragmentScenario

我正在尝试使用 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。 所以我不知道如何测试用户与菜单的交互。

我通过传递一个虚拟菜单项解决了这个问题:

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

编辑:这个解决方案在当时挽救了一天。 但是现在我开始更喜欢将工具栏放在片段布局中而不是活动中,尤其是如果我为不同的片段设置了不同的菜单,那么我在其他项目中就不会遇到同样的问题。 这也是一个可能的解决方案。

您还可以使用 mockito 模拟菜单项。像这样:

val menuItemMock = mock<ActionMenuItem> {
   on { itemId } doReturn R.id.action_item
}

       
launchFragmentInContainer { YourFragment().also{ /*initialize*/ } }
.onFragment {
    it.onOptionsItemSelected(menuItemMock)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM