gpt4 book ai didi

android - 如何使用 Hilt 模拟 View 模型以进行单元测试 fragment ?

转载 作者:行者123 更新时间:2023-12-02 12:03:01 26 4
gpt4 key购买 nike

我有一个使用 Hilt 进行依赖注入(inject)的 android 应用程序设置,并且想对我的 fragment 进行单元测试。
我目前正在使用以下方法创建我的 View 模型:

private val viewModel: ExampleViewModel by viewModels()
我正在使用 here 中的代码创建用于测试的 fragment
我需要用一个模拟替换这个 ExampleViewModel,我该怎么做呢?

最佳答案

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

Hilt ViewModel extension works by declaring modules that bind assistedfactories to a map and not by binding concrete ViewModels. Therefore,what you want to do is bind the assisted factory of the concreteViewModel using the key of the abstract ViewModel so that whenHiltViewModelFactory looks up the factory based on class key it usesthe assisted factory for the concrete ViewModel. This is suuuperobscure and hence why I mean not 'easily' available.

However, if you can expand on the test case your are trying to writethat could help us provide some guidance, I'm not sure if you aretrying to mock/fake the ViewModel itself for tests, but Hilt testingAPIs should allow you to replace dependencies in the ViewModel so youcan write a test with the Fragment and the ViewModel.

关于android - 如何使用 Hilt 模拟 View 模型以进行单元测试 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62823817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com