airbnb / mavericks

Mavericks: Android on Autopilot
https://airbnb.io/mavericks/
Apache License 2.0
5.83k stars 500 forks source link

mavericks-mocking and @assisted-inject throws No ViewModelFactoriesFieldInjector found. #610

Closed sanginovs closed 2 years ago

sanginovs commented 2 years ago

Hi @elihart When using mavericks-mocking with viewModels which use Dagger's @assistedInject, I keep getting this runtime error. Any idea on how to fix this?

Caused by: java.lang.IllegalArgumentException: No ViewModelFactoriesFieldInjector found.

Here's the code that throws this error (My assistedInject setup is similar to mavericks assisted inject sample project):


class DaggerMavericksViewModelFactory<VM : MavericksViewModel<S>, S : MavericksState>(
    private val viewModelClass: Class<VM>
) : MavericksViewModelFactory<VM, S> {

    override fun create(viewModelContext: ViewModelContext, state: S): VM {
        val viewModelFactoryMap =
            ((viewModelContext.activity as? FieldInjectorProvider)?.injector as? ViewModelFactoriesFieldInjector)
                ?.viewModelFactories()
                ?: throw IllegalArgumentException("No ViewModelFactoriesFieldInjector found.")
        val viewModelFactory = viewModelFactoryMap[viewModelClass]

        @Suppress("UNCHECKED_CAST")
        val castedViewModelFactory = viewModelFactory as? AssistedViewModelFactory<VM, S>
        val viewModel = castedViewModelFactory?.create(state)
        return viewModel as VM
    }
}```
elihart commented 2 years ago

Are you talking about using mocks from the launcher? in general the mocking was not necessarily designed to work with assisted inject so the ViewModelFactoriesFieldInjector isn't set up on the launcher activity. You may need to make some changes for them to be compatible