Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

android - How to mock a Jetpack Datastore in a Espresso

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>>()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...