【问题标题】:Mock dagger 2 modules while using factory使用工厂时模拟 dagger 2 模块
【发布时间】: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


    【解决方案1】:

    不要模拟共享偏好或上下文。我们知道这些 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")
    

    【讨论】:

    • 如果这个类可以通过dagger 2作为服务注入,你能提供一个例子吗?
    • 不确定您的意思?将 Context 或 SharedPreferences 提供为可注入并将此类注释为可注入或为其创建提供。如果需要将其用作服务的一部分,则在服务生命周期的某个阶段将其注入。
    猜你喜欢
    • 2016-07-29
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多