I've got an android app setup for dependency injection using Hilt, and would like to unit test my fragments.
I'm currently creating my view model using:
private val viewModel: ExampleViewModel by viewModels()
And I am creating the fragment for testing using the code from here
I need to replace this ExampleViewModel with a mock, how would I go about doing this?
I will paste here the "danysantiago" response in a issue (https://github.com/google/dagger/issues/1972) related to your question:
Hilt ViewModel extension works by declaring modules that bind assisted factories to a map and not by binding concrete ViewModels. Therefore, what you want to do is bind the assisted factory of the concrete ViewModel using the key of the abstract ViewModel so that when HiltViewModelFactory looks up the factory based on class key it uses the assisted factory for the concrete ViewModel. This is suuuper obscure and hence why I mean not 'easily' available.
However, if you can expand on the test case your are trying to write that could help us provide some guidance, I'm not sure if you are trying to mock/fake the ViewModel itself for tests, but Hilt testing APIs should allow you to replace dependencies in the ViewModel so you can write a test with the Fragment and the ViewModel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With