首页 > 解决方案 > 如何对具有泛型类型的 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")
    }
}

测试具有泛型类型的扩展函数的最佳方法是什么?

非常感谢您的任何建议,

标签: androidunit-testingkotlinkotlin-extension

解决方案


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


推荐阅读