rkeazor
03/19/2024, 12:20 AMgalex
03/19/2024, 1:08 PMinline fun <reified T : ViewModel> launchInAssistedHiltContainer(noinline factory: () -> ViewModelProvider.Factory, crossinline block: (T) -> Unit) = run {
launchFragmentInHiltContainer<EmptyFragment>().onFragment {
val viewModel = it.viewModels<T>(
factoryProducer = factory
)
block(viewModel.value)
}
}
and
inline fun <reified F : Fragment> launchFragmentInHiltContainer(
fragmentArgs: Bundle? = null,
@StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme,
initialState: Lifecycle.State = Lifecycle.State.RESUMED,
factory: FragmentFactory? = null,
): HiltFragmentScenario<F> = HiltFragmentScenario.launchInHiltContainer(
F::class.java, fragmentArgs, themeResId, initialState,
factory
)
Built on top of https://developer.android.com/training/dependency-injection/hilt-testing#launchfragment
But I would advise to not use Hilt for testing, as it requires all dependencies of a module to be met even if the VM you want to test doesn't use those dependencies.
It created a TON of boilerplate code in our tests and we just create a new VM ourselves now.
Hope this helpsrkeazor
03/19/2024, 2:12 PM