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.
question from:
https://stackoverflow.com/questions/65618104/how-to-mock-a-jetpack-datastore-in-a-espresso 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…