Oya*_*nlı 8 android menu ui-testing fragment android-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.
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如何将正确的项目传递给 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)
}
Run Code Online (Sandbox Code Playgroud)
编辑:这个解决方案在当时挽救了一天。但是现在我开始更喜欢将工具栏放在片段布局中而不是活动中,尤其是如果我为不同的片段设置了不同的菜单,那么我在其他项目中就不会遇到同样的问题。这也是一个可能的解决方案。
归档时间: |
|
查看次数: |
440 次 |
最近记录: |