11

I use dagger hilt in my project. I want to write UI test for some fragments. I need to mock the viewModel in the test class and associate it to the fragment under the test.. I read dagger hilt document but I didn't find any solution.

   class HomeViewModel @ViewModelInject constructor(
    private val repository: MainRepository,
    prefManager: PrefManager,
    private val firebaseAnalytics: FirebaseAnalytics,
    @Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
 /////
}

    @AndroidEntryPoint
class HomeFragment : BaseFragment() {

    private val viewModel: HomeViewModel by viewModels()
/////
}
maryam
  • 1,437
  • 2
  • 18
  • 40

1 Answers1

2

If your goal is to test your fragment with mock data, you don't have to mock the view model; instead, you can provide mock repository implementation in a dagger module:

@Module
@TestInstallIn(
    components = SingletonComponent::class,
    replaces = ProdRepositoryModule::class
)
interface FakeRepositoryModule {
  @Binds fun bind(impl: FakeRepository): MainRepository
}

When running UI tests, this will replace all the bindings provided in the ProdRepositoryModule module with the bindings provided in the FakeRepositoryModule module. Check out the Hilt Testing documentation for further assistance.

Levon Petrosyan
  • 8,815
  • 8
  • 54
  • 65