使用Mockito中的访问器模拟Kotlin属性 [英] Mocking kotlin property with accessors in Mockito
问题描述
我的应用程序类(Kotlin)中有一个基于SharedPreferences值的令牌属性
I have a token property in my application class(Kotlin) that is based on a SharedPreferences value
var token : String?
get() = PreferenceManager.getDefaultSharedPreferences(applicationContext)
.getString(TOKEN_PEREF_TAG, null)
set(value) {
PreferenceManager.getDefaultSharedPreferences(applicationContext)
.edit()
.putString(TOKEN_PEREF_TAG, value)
.apply()
}
问题是我无法设置这样的模拟值:
The problem is that I can't set a mock value like this:
whenever(app.token).thenReturn("token")
因为我得到了错误
java.lang.RuntimeException:android.preference.PreferenceManager中的方法getDefaultSharedPreferences不被模拟.
java.lang.RuntimeException: Method getDefaultSharedPreferences in android.preference.PreferenceManager not mocked.
模拟不应该只返回提供的字符串吗?
Shouldn't the mock just return the provided string?
如何解决该错误?
推荐答案
您可以通过使用mockito-inline
依赖性而不是mockito-core
依赖性来解决此错误.这使用了一种不同的模拟方法来避免平台类不可用的问题.它也特别有用,因为它允许您模拟最终课程,因此无需将每个课程都放在一个界面,或在Kotlin中将其标记为open
.
You can fix this error by using the mockito-inline
dependency instead of the mockito-core
dependency. This uses a different mocking method that circumvents this issue of the platform classes not being available. It's also particularly useful because it allows you to mock final classes, therefore eliminating the need to put every one of your classes behind an interface or mark them as open
in Kotlin.
This inline mocking method can also be turned on by a configuration file, however I found just using the inline dependency much more reliable.
这篇关于使用Mockito中的访问器模拟Kotlin属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!