首页 > 解决方案 > AndroidX 测试 - ActivityScenario onView() 找不到嵌套的子片段

问题描述

我有一个活动MyActivity,它又包含一个片段MyFragment。在MyFragment我显示一个 BottomSheetDialogFragment 使用childFragmentManager如下:

bottomSheetFragment.show(childFragmentManager, "BottomSheetFragment")

下面是我在 JVM 中运行的测试用例(使用 AndroidX 测试/Robolectric)。

  @Test
  fun isBottomSheetShownTest() {
    val scenario = ActivityScenario.launch(MyActivity::class.java)

    FakeViewModle.showBottomSheet() // Posts on a LiveData to show the bottom sheet

    scenario.onActivity {
      val fragment = it.supportFragmentManager.fragments[0]
      val bottomSheet = fragment.childFragmentManager.findFragmentByTag("BottomSheetFragment")!!
      val view = bottomSheet.view!!
      val findViewById = view.findViewById<View>(R.id.bottomSheetTitle)
      val visibility = findViewById.visibility // View is present and Visible
    }

    Espresso.onView(ViewMatchers.withId(R.id.bottomSheetTitle)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)))
    // Throws androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching
  }

上述测试用例因“androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching”而失败。但在 中scenario.onActivity {},我可以看到膨胀的 BottomSheet 片段。在调试时,我发现 BottomSheet 完全膨胀,因为它处于 Resumed 状态。

我的问题是:

  1. Espresso.onView()持有什么?当我检查视图层次结构时,我看到了 MyActivity 和 MyFragment,但没有看到 BottomSheet。

  2. 是否无法使用 获取嵌套的子片段Espresso.onView()

  3. Espresso.onView()如何通过使用而不是查询来断言我的 BottomSheet 中是否存在视图scenario.onActivity

标签: androidandroid-fragmentsandroid-espressorobolectricandroidx-test

解决方案


推荐阅读