AndroidX Test - ActivityScenario onView() can't find nested child fragment

1.1k Views Asked by At

I have an activity MyActivity which in turn holds a fragment MyFragment. In MyFragment I show a BottomSheetDialogFragment using the childFragmentManager as below:

bottomSheetFragment.show(childFragmentManager, "BottomSheetFragment")

The below is my test case (using AndroidX test / Robolectric) running in JVM.

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

The above test case fails with "androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching". But within the scenario.onActivity {}, I am able to see the inflated BottomSheet fragment. On debugging, I found that the BottomSheet is fully inflated as is in Resumed state.

My Questions are:

  1. What does Espresso.onView() hold? When I checked the View hierarchy, I see the MyActivity and MyFragment but not the BottomSheet.

  2. Is it not possible to get the nested child fragment using Espresso.onView() ?

  3. How do I assert if a View is present in my BottomSheet, by using Espresso.onView() instead of querying the scenario.onActivity ?

0

There are 0 best solutions below