【发布时间】:2020-05-26 18:28:04
【问题描述】:
我正在使用 dagger 2 的 android 功能。
我的 AppComponent 如下所示:
@Singleton
@Component(modules = [AppModule::class])
interface ApplicationComponent : AndroidInjector<MyApplication> {
@Component.Factory
abstract class Builder : AndroidInjector.Factory<MyApplication>
}
还有我的 AppModule:
@Module(includes = [AndroidInjectionModule::class])
abstract class AppModule {
@Singleton
@Binds
@AppContext
abstract fun provideContext(app: MyApplication): Context
}
我尝试模拟这个模块和其他模块(当它们出现时)。我读过 using @Component.factory is better than builder 但我不知道如何模拟它。
我尝试如下模拟SharedPreferences,但我认为,我还必须提供模拟的Context。
val sharedPrefs: SharedPreferences = Mockito.mock(SharedPreferences::class.java)
val context: Context = Mockito.mock(Context::class.java)
Mockito.`when`(context.getSharedPreferences(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt())).thenReturn(sharedPrefs)
Mockito.`when`(sharedPrefs.getString(anyString(), anyString())).thenReturn(AuthType.UNDEFINED.toString())
如何模拟Context并提供模拟的SharedPreferences?
【问题讨论】:
标签: android junit mockito dagger-2