如何使用 Hilt 模拟视图模型以进行单元测试片段? [英] How to mock the view model with Hilt for unit testing fragments?

查看:27
本文介绍了如何使用 Hilt 模拟视图模型以进行单元测试片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()

我正在使用 这里

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

I need to replace this ExampleViewModel with a mock, how would I go about doing this?

推荐答案

我将在这里粘贴danysantiago"对问题的回应 (https://github.com/google/dagger/issues/1972) 与您的问题相关:

I will paste here the "danysantiago" response in a issue (https://github.com/google/dagger/issues/1972) related to your question:

Hilt ViewModel 扩展通过声明绑定辅助的模块来工作工厂到地图,而不是通过绑定具体的 ViewModel.所以,你要做的是绑定混凝土的辅助工厂ViewModel 使用抽象 ViewModel 的键,这样当HiltViewModelFactory 根据它使用的类键查找工厂具体 ViewModel 的辅助工厂.这是超级晦涩难懂,因此我的意思是不容易"获得.

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.

但是,如果您可以扩展您正在尝试编写的测试用例这可以帮助我们提供一些指导,我不确定你是否试图模拟/伪造 ViewModel 本身进行测试,但 Hilt 测试API 应该允许您替换 ViewModel 中的依赖项,以便您可以用 Fragment 和 ViewModel 编写测试.

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.

这篇关于如何使用 Hilt 模拟视图模型以进行单元测试片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆