我正在使用带有匕首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
}
我尝试模拟此模块和其他模块(当它们出现时)。我读过使用@Component.factory
比构建器更好,但我不知道如何模拟它。
我尝试如下模拟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
?
答案 0 :(得分:0)
请勿嘲笑共享的首选项或上下文。我们知道这些android实现可以正常工作,不需要进行测试。
创建一个包装类,可以将其用作可模拟的接口,以便对您的首选项进行单元测试。
class MyClassPreferences(context: Context) {
val preferences: SharedPreferences = context.getSharedPreferences("", MODE_PRIVATE)
fun getPreferenceOne(): String {
return preferences.getString(KEY, "")
}
fun setPreferenceOne(value: String) {
preferences.edit().putString(KEY, value).commit()
}
}
正在测试
Mockito.`when`(myClassPreferences.getPreferenceOne()).thenReturn("value")