使用 FragmentScenario.EmptyFragmentActivity 测试 AppCompatActivity 工具栏

the*_*ole 5 android android-espresso android-fragmentscenario

对于我的测试,我在空活动根视图容器中启动片段

@Before
fun init() {
    scenario = launchFragmentInContainer(null, R.style.Theme_AppCompat) {
        MyFragment()
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的片段中,我配置工具栏以提供后退按钮

(activity as AppCompatActivity).setSupportActionBar(binding.toolbar)
(activity as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)
Run Code Online (Sandbox Code Playgroud)

所以当我运行测试时,我得到一个类强制转换异常

java.lang.ClassCastException: androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity cannot be cast to androidx.appcompat.app.AppCompatActivity
Run Code Online (Sandbox Code Playgroud)

所以我必须添加一个守卫

if(requireActivity() !is FragmentScenario.EmptyFragmentActivity)
    configureToolBar()    
Run Code Online (Sandbox Code Playgroud)

那么是否有另一种方法来配置工具栏,以便我可以使用 espresso 测试后退按钮意图启动?

编辑

显然有一种方法可以创建自定义活动/容器。