Hi there, I have one issue in testing a viewModel ...
# dagger
i
Hi there, I have one issue in testing a viewModel with Hilt let's assume we have this viewModel:
Copy code
@HiltViewModel
open class BottomSheetViewModel @Inject constructor(
    val savedStateHandle: SavedStateHandle,
    val someRepository: SomeRepository,
)

where SomeRepository is:

@Singleton
open class SomeRepository@Inject constructor(
@ApplicationContext private val context:Context,
 private val appLogManager: AppLogManager
)
so as you see one of the constructor parameters is savedStateHandle and because of that I can not inject that in test like this:
Copy code
@Inject
lateinit var bottomSheetViewModel: BottomSheetViewModel
so as far as I see, seems the best practice for this is mocking, so I am trying to mock the viewModel like this:
Copy code
@BindValue
   val bottomSheetViewModel = mock<BottomSheetViewModel>()
Am I right so far? but the problem is I get some errors when I create a mock from the viewModel
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class com.zabanshenas.tools.base.BaseViewModel.
Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
I resolve it with this approach currently🙄 Although it works, I don't like it🥲
Copy code
@Inject lateinit var  someRepository: SomeRepository

@Before
fun setup() {
    hiltRule.inject()
    val savedStateHandle = SavedStateHandle()
    bottomSheetViewModel = BottomSheetViewModel(
        savedStateHandle = savedStateHandle,
        someRepository = SomeRepository
    )
}
but the thing is we can not inject any viewModel assigned with @HiltViewModel in general and it doesn't matter to have a SavedStateHandle in constructor parameter or not
Injection of an @HiltViewModel class is prohibited since it does not create a ViewModel instance correctly.
106 Views