android - 如何对具有泛型类型的 kotlin 扩展函数进行单元测试
问题描述
kotlin 1.2.51
我有以下使用通用扩展功能的共享偏好。
class SharedUserPreferencesImp(private val context: Context,
private val sharedPreferenceName: String): SharedUserPreferences {
private val sharedPreferences: SharedPreferences by lazy {
context.getSharedPreferences(sharedPreferenceName, Context.MODE_PRIVATE)
}
override fun <T : Any> T.getValue(key: String): T {
with(sharedPreferences) {
val result: Any = when (this@getValue) {
is String -> getString(key, this@getValue)
is Boolean -> getBoolean(key, this@getValue)
is Int -> getInt(key, this@getValue)
is Long -> getLong(key, this@getValue)
is Float -> getFloat(key, this@getValue)
else -> {
throw UnsupportedOperationException("Cannot find preference casting error")
}
}
@Suppress("unchecked_cast")
return result as T
}
}
}
我正在尝试为此方法编写单元测试。正如您在我的测试方法中看到的那样,testName.getValue("key")
无法getValue
识别。
class SharedUserPreferencesImpTest {
private lateinit var sharedUserPreferences: SharedUserPreferences
private val context: Context = mock()
@Before
fun setUp() {
sharedUserPreferences = SharedUserPreferencesImp(context, "sharedPreferenceName")
assertThat(sharedUserPreferences).isNotNull
}
@Test
fun `should get a string value from shared preferences`() {
val testName = "this is a test"
testName.getValue("key")
}
}
测试具有泛型类型的扩展函数的最佳方法是什么?
非常感谢您的任何建议,
解决方案
T.getValue(key: String)
作为扩展函数和 SharedUserPreferencesImp 成员函数之间存在冲突。您可以制作T.getValue(key: String)
高级功能,这解决了一个问题。这是示例代码:
fun <T : Any> T.getValue(key: String, sharedPreferences: SharedUserPreferencesImp): T {
with(sharedPreferences.sharedPreferences) {
val result: Any = when (this@getValue) {
is String -> getString(key, this@getValue)
is Boolean -> getBoolean(key, this@getValue)
is Int -> getInt(key, this@getValue)
is Long -> getLong(key, this@getValue)
is Float -> getFloat(key, this@getValue)
else -> {
throw UnsupportedOperationException("Cannot find preference casting error")
}
}
@Suppress("unchecked_cast")
return result as T
}
}
class SharedUserPreferencesImp(private val context: Context,
private val sharedPreferenceName: String): SharedUserPreferences {
val sharedPreferences: SharedPreferences by lazy {
context.getSharedPreferences(sharedPreferenceName, Context.MODE_PRIVATE)
}
}
你也可以看看这两个很棒的库: https ://github.com/chibatching/Kotpref https://github.com/MarcinMoskala/PreferenceHolder
推荐阅读
- javascript - How to rotate a image "file" in javascript and then return that rotated image as a file
- python - Subset df between two strings values - pandas
- compiler-errors - AMPL: error processing param: invalid subscripts discarded
- tensorflow - Val_accuracy 和 Accuracy 具有独立于编译模型的常数值 - Tensorflow 2.0
- python-3.x - Python-网络抓取,函数中的for循环不起作用
- linux - 在 Ubuntu linux 中创建一个二进制安装程序,并使用 cmake 从源代码中创建依赖项
- c# - 我想使用 C# 验证所有行上的特定单元格
- javascript - 排序和替换对象键值 - Javascript
- angular - 如何使用蚂蚁设计以角度创建动态网格视图?
- mysql - 你如何将一个每行有 1 个值的表内部连接到另一个每行有 2 个值的表,在 MySQL 中用逗号分隔?