在Mockito嘲笑kotlin财产与访问者

时间:2018-02-16 19:54:03

标签: android kotlin mockito

我的应用程序类(Kotlin)中有一个基于SharedPreferences值的标记属性

    var token : String?
    get() = PreferenceManager.getDefaultSharedPreferences(applicationContext)
               .getString(TOKEN_PEREF_TAG, null)
    set(value) {
    PreferenceManager.getDefaultSharedPreferences(applicationContext)
            .edit()
            .putString(TOKEN_PEREF_TAG, value)
            .apply()
    }

问题在于我无法像这样设置模拟值:

whenever(app.token).thenReturn("token")

因为我收到了错误

  

java.lang.RuntimeException:android.preference.PreferenceManager中的方法getDefaultSharedPreferences没有被模拟。

模拟器不应该返回提供的字符串吗?

如何解决此错误?

2 个答案:

答案 0 :(得分:4)

您可以使用mockito-inline依赖项而不是mockito-core依赖项来修复此错误。这使用了一种不同的模拟方法来避免平台类的这个问题无法使用。它也特别有用,因为它允许你mock final classes,因此无需将每个类放在界面后面或在Kotlin中将它们标记为open

此内联模拟方法也可以由configuration file启用,但我发现只使用内联依赖项更加可靠。

答案 1 :(得分:0)

在'小测试'(jUnit测试,src / test中的测试)中,android框架不存在,整个框架只是一个存根,不提供任何功能。您必须使用mockito或类似的方式创建自己的模拟SharedPreferencesPreferenceManager。或者使用必须在模拟器或设备上运行的“中等测试”(仪器化测试,src / androidTest中的测试)。有关此检查的更多信息Fundamentals of Testing