如何使用 Hilt 模拟视图模型以进行单元测试片段?

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

我有一个 android 使用 Hilt 进行依赖项注入的应用程序设置,并且想对我的片段进行单元测试。

我目前正在使用以下方法创建我的视图模型:

private val viewModel: ExampleViewModel by viewModels()

我正在使用 here

中的代码创建用于测试的片段

我需要用模拟替换这个 ExampleViewModel,我该怎么做?

我将在此处粘贴与您的问题相关的问题 (https://github.com/google/dagger/issues/1972) 中的“danysantiago”回复:

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.