Как выполнить модульное тестирование функции расширения kotlin, имеющей универсальный тип - PullRequest
0 голосов
/ 10 марта 2019
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")
    }
}

Как лучше всего протестировать функцию расширения, имеющую универсальный тип?

Большое спасибо за любые предложения,

1 Ответ

1 голос
/ 10 марта 2019

Конфликт между 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

...