Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock the view model with Hilt for unit testing fragments?

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?

like image 596
kmell Avatar asked Jul 09 '20 21:07

kmell


Video Answer


1 Answers

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.

like image 82
Cassio Landim Avatar answered Nov 12 '22 02:11

Cassio Landim