Is it possible to Mock out Hilt Assisted viewmodel...
# dagger
r
Is it possible to Mock out Hilt Assisted viewmodel dependencies?
g
Yes, like that
Copy code
inline 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
Copy code
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 helps
r
Hey thanks for the response, this is helpful. I think i have to use hilt for espresso testing, if im using hilt in the prod code
👍 1