Search code examples
androidandroid-fragmentsfragmentandroid-testingandroidx

How to get fragment instance from Fragment Scenario


In my test case i want to get the view of the fragment that I launched in fragment scenario like this:

val scenario = launchFragment<MyFragment>()

In MyFragment I've got a method rootView that returns the bindet view of the fragment. In my test I want to get the root view and save it in another field. This is what I've been tried

val rootView: ViewGroup? = null
val scenario = launchFragment<MyFragment>()
scenario.onFragment { fragment -> fragment.rootView {
     rootView = fragment.rootView
  }

How can I save the the view from the fragment scenario?


Solution

  • A late answer, but in case anyone else needs it:

    val root: View? = null
    val scenario = launchFragment<MyFragment>()
    scenario.onFragment { fragment ->
        root = fragment.view?.rootView
    }