首页 > 解决方案 > 在 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 提供的作用域依赖项?

标签: androidunit-testingdagger-hilt

解决方案


推荐阅读