ali*_*ter 9 android dagger dagger-hilt
我正在使用 Hilt 注入一些依赖项,如下所示:
@Module
@InstallIn(SingletonComponent::class)
object SomethingModule {
@Provides
fun provideSomething(@ApplicationContext context: Context): Something {
//return RealSomething
}
}
Run Code Online (Sandbox Code Playgroud)
我想在我的测试中替换此绑定,并按照本指南将这个假模块添加到与我的仪器测试相同的文件夹中:
@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [SomethingModule::class]
)
object FakeSomethingModuleModule {
@Provides
fun provideSomethingModule(): Something {
return FakeSomething()
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试运行仪器测试时,构建失败并出现重复的绑定错误:
error: [Dagger/DuplicateBindings] com.example.Something is bound multiple times:
public abstract static class SingletonC implements HiltWrapper_ActivityRetainedComponentManager_ActivityRetainedComponentBuilderEntryPoint,
Run Code Online (Sandbox Code Playgroud)
注释掉 Fake Module 可以解决该问题。有人看到我在这里缺少什么吗?
编辑:刚刚尝试并@UninstallModules遇到了相同的构建错误:
@UninstallModules(SomethingModule::class)
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class MyInstrumentedTest {
@Module
@InstallIn(SingletonComponent::class)
object FakeSomethingModule {
@Provides
fun provideSomthing(): Something = FakeSomething()
}
Run Code Online (Sandbox Code Playgroud)
为了最终找到解决方案,我尝试了很多不同的方法:
确保假的实现有@Inject constructor()
在测试中@Module使用@Binds抽象类而不是@Provides
您不需要组合所有模块的组件,以下代码不是必需的:
@Module(
includes = [ <modules> ]
Run Code Online (Sandbox Code Playgroud)
@Module(includes = SomethingBinding). 我专门为我想在仪器测试中模拟的对象创建了一个模块| 归档时间: |
|
| 查看次数: |
1739 次 |
| 最近记录: |