1

I switched from SharedPreferences to Jetpack DataStore.

I am unable to mock the data from the datastore call in the Instrumentation test

In declaration

 val dataStore = context.createDataStore(name = "App Name")

In the declaration get a string from preferences

   suspend fun getString(
        key: Preferences.Key<String>,
        defaultVal: String,
        context: Context
    ): String {
        return dataStore?.data?.catch {
            if (it is IOException) {
                it.printStackTrace()
                emit(emptyPreferences())
            } else {
                throw it
            }
        }?.map {
            it[key] ?: defaultVal
        }?.first() ?: ""
    }

In the usage

 SharedPreferenceHelper.getString(
                Preferences.Key<T>,
                "",
                requireContext()
            )

Manipulate datastore preferences string key to get mocked value in instrumentation test as the desired value.

Thank you in advance.

SURYA N
  • 299
  • 2
  • 16

1 Answers1

1

createDataStore returns DataStore<Preference>, this will help you to create mock of Class with generic type

Or you can use mockito-kotlin to create mock like this in kotlin

 val mockDataStore = mock<DataStore<Preference>>()
iamanbansal
  • 2,412
  • 2
  • 12
  • 20