google / dagger

A fast dependency injector for Android and Java.
https://dagger.dev
Apache License 2.0
17.41k stars 2.01k forks source link

launchFragmentInHiltContainer cannot create Fragment #3181

Closed hongbeomi closed 2 years ago

hongbeomi commented 2 years ago
@AndroidEntryPoint
class A: Fragment() {
  val viewModel by viewModels<AViewModel>(ownerProducer = { requireParentFragment() })
}

In the case of the above code, the following error occurs when attempting to generate the AFragment as a launchFragmentInHiltContainer when writing a test code.

java.lang.IllegalStateException: Fragment AFragment{b6d6154}  is not a child Fragment, it is 
directly attached to dagger.hilt.android.internal.managers.ViewComponentManager$FragmentContextWrapper
dmapr commented 2 years ago

You can replace requireParentFragment() with parentFragment() ?: this as a workaround for testing although it will rob you of the IllegalStateException being thrown when fragment is being used without a parent.

Chang-Eric commented 2 years ago

The lack of a parent fragment in the test is the likely issue. I think the better workaround though would be to make your test more closely approximate your production code by actually wrapping your child fragment in a parent Hilt fragment in your test. So instead of using launchFragmentInHiltContainer (which just uses a Hilt activity) to launch your fragment directly, I would create a test parent Hilt fragment that just adds the fragment under test to itself, and then use launchFragmentInHiltContainer on your test parent fragment.

hongbeomi commented 2 years ago

Thank you! @dmapr @Chang-Eric