【发布时间】:2022-12-10 07:35:45
【问题描述】:
在不同的教程中,我看到了如何将 @Component 的依赖项替换为 mock 或 fakes。为此,可以使 @Component 的测试变体扩展常规版本。但是我还没有找到如何对@Subcomponent 做同样的事情。
这是我的设置。零件:
@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {
fun plus(userModule: UserModule): UserComponent
...
}
组件的测试版本:
@Singleton
@Component(modules = [TestAppModule::class])
interface TestAppComponent: AppComponent
子组件:
@UserScope
@Subcomponent(modules = [UserModule::class])
interface UserComponent
用法:
@Before
fun setUp() {
MockKAnnotations.init(this)
val loginManagerMock = mockk<LoginManager>()
val testAppModule = TestAppModule(
context = app,
loginManager = loginManagerMock
)
val appComponent = DaggerTestAppComponent.builder()
.testAppModule(testAppModule)
.build()
val testUserModule = TestUserModule(
context = app,
userEmail = "testing@mail.com",
pdaRepository = pdaRepositoryMock
)
val userComponent = appComponent.plus(testUserModule) // this is not working
every { loginManagerMock.userComponent } returns userComponent
app.appComponent = appComponent
}
问题是我不能像实例化@Component 那样实例化@Subcomponent。我必须使用 AppComponent 的 plus(userModule: UserModule): UserComponent 方法。 TestAppModule 不可能扩展 AppModule 并覆盖 @Provides 方法。
如果有人能告诉我如何用模拟或假货替换@Subcomponent 的 UserModule 提供的依赖项,我将不胜感激?
【问题讨论】:
标签: unit-testing mocking dagger-2 dagger