android - 在 Android 中使用 Dagger Hilt 处理单元测试中的作用域依赖项
问题描述
我有一个使用 Dagger Hilt 进行依赖注入的应用程序。我正在为视图模型编写单元测试,但我收到错误,因为视图模型具有的某些依赖项已被注释,@ViewModelScoped
并且 Hilt 规则只能注入@Singleton
组件。
视图模型签名是
@HiltViewModel
class AboutViewModel @Inject constructor(
private val settingsInteractor: SettingsInteractor,
private val stringLookup: StringLookup,
private val navigator: AboutNavigator,
private val settingsTelemetry: SettingsTelemetry,
)
并且SettingsTelemetry
定义为
@ViewModelScoped
class SettingsTelemetry @Inject constructor(
/* omitted dependencies */
)
并且测试目前被定义为这个
@HiltAndroidTest
@Config(application = HiltTestApplication::class)
@RunWith(RobolectricTestRunner::class)
class AboutViewModelTest {
@get:Rule
val instantExecutorRule = InstantTaskExecutorRule()
@get:Rule
val hiltRule = HiltAndroidRule(this)
@get:Rule
val scope: CoroutineScopeTestRule = CoroutineScopeTestRule()
@Inject
lateinit var aboutViewModel: AboutViewModel
@Before
fun init() {
hiltRule.inject()
}
@Test
fun `sample test`() {
Assert.assertTrue(true)
}
}
我得到的错误是
/home/user/Projects/sample/presentation/feature/settings/build/generated/source/kapt/androidDebugUnitTest/com/example/settings/about/viewmodel/AboutViewModelTest_HiltComponents.java:294:
error: [Dagger/IncompatiblyScopedBindings] com.example.settings.about.viewmodel.AboutViewModelTest_HiltComponents.SingletonC scoped with @Singleton may not reference bindings with different scopes
如何在单元测试中获取 Dagger 提供的作用域依赖项?
解决方案
推荐阅读
- python - 从 Pandas 数据框列中提取多个子字段到一个新的数据框中
- php - 为什么我在博客中找不到帖子的页面?
- r - (多)多边形的反向坐标
- javascript - Microsoft Edge PDF 查看器扩展位置
- python - 安装后缺少 pywin32_postinstall.py
- asp.net-core - EF核心多对多与连接表获取数据
- python-3.x - 如何解决 Windows 10 中 pytorch 的多处理问题
- mysql - docker compose 无法附加到 mysql windows 的端口
- python - pygame中的音量控制
- variables - 可变通过动态管道