浓缩咖啡测试失败

cor*_*her 7 android android-fragments android-testing android-navigation android-espresso

我正在 Android 中进行一些 Espresso 测试。测试失败并出现此错误:

java.lang.ClassCastException: androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity 无法转换为 com.stavro_xhardha.pockettreasure.MainActivity

这是我的测试方法:

@Test
fun toolbarTitle_shouldContainCorrectInput() {
    val mockNavController = mock(NavController::class.java)
    val fragmentScenario = launchFragmentInContainer<SetupFragment>()
    fragmentScenario.onFragment {
        Navigation.setViewNavController(it.view!! , mockNavController)
    }
    onView(withId(R.id.toolbar)).check(matches(withText("Pick your country")))
}
Run Code Online (Sandbox Code Playgroud)

但是错误不是来自 Test 类,而是来自我的 Fragment under test 。崩溃是在这行代码中执行的:

override fun onStart() {
    super.onStart()
    (activity!! as MainActivity).supportActionBar?.hide() //here
}
Run Code Online (Sandbox Code Playgroud)

我不明白的是,当我在没有测试的情况下正常运行应用程序时,我没有遇到任何错误。

Dmi*_*yai 18

这是完整的答案。
关于launchFragmentInContainer- 它接受给定的片段并在内部EmptyFragmentActivity类中启动它? - 将片段放在根视图容器中。
因此,它应该仅用于检查片段,而不依赖于它的父活动。

在您的情况下,您尝试在您正在测试的片段中隐藏一个操作栏。但是在测试中,您的片段不会在 MainActivity 中启动。
如果你只想检查片段,而不是(activity!! as MainActivity).supportActionBar?.hide()你需要写这样的东西:

if(activity!! is MainActivity){
    activity?.supportActionBar?.hide()
}
Run Code Online (Sandbox Code Playgroud)

或者您应该为您的 MainActivity 或您使用片段的地方编写测试