如何模拟喷气背包首选项存储 (Context.createDataStore(PackageName))

时间:2021-02-16 14:35:38

标签: android unit-testing kotlin android-preferences mockk

所以我一直在使用 Jetpack Preference DataStore 来存储我的本地数据。所以我尝试对 DataStore 进行单元测试,但我无法测试。 DataStore 在调用 context.createDataStore()

时抛出空指针异常
mApplicationContext.createDataStore(name = mApplicationContext.packageName)

这是我得到的异常。

Exception in thread "main @coroutine#9" java.lang.NullPointerException
    at java.io.File.<init>(File.java:363)
    at androidx.datastore.preferences.PreferenceDataStoreFactoryKt$createDataStore$1.invoke(PreferenceDataStoreFactory.kt:63)
    at androidx.datastore.preferences.PreferenceDataStoreFactoryKt$createDataStore$1.invoke(PreferenceDataStoreFactory.kt)
    at androidx.datastore.preferences.core.PreferenceDataStoreFactory$create$delegate$1.invoke(PreferenceDataStoreFactory.kt:69)
    at androidx.datastore.preferences.core.PreferenceDataStoreFactory$create$delegate$1.invoke(PreferenceDataStoreFactory.kt:32)
    at androidx.datastore.core.SingleProcessDataStore$file$2.invoke(SingleProcessDataStore.kt:101)
    at androidx.datastore.core.SingleProcessDataStore$file$2.invoke(SingleProcessDataStore.kt:61)
    at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
    at androidx.datastore.core.SingleProcessDataStore.getFile(SingleProcessDataStore.kt)
    at androidx.datastore.core.SingleProcessDataStore.readData(SingleProcessDataStore.kt:248)
    at androidx.datastore.core.SingleProcessDataStore.readDataOrHandleCorruption(SingleProcessDataStore.kt:227)
    at androidx.datastore.core.SingleProcessDataStore.readAndInitOnce(SingleProcessDataStore.kt:190)
    at androidx.datastore.core.SingleProcessDataStore$actor$1.invokeSuspend(SingleProcessDataStore.kt:154)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

当我问我的同事时,他提到 createDataStore() 函数是在一个文件中定义的,并且是从 Context 类中调用的。我一直在为这个单元测试寻找解决方案。谁能帮帮我。

0 个答案:

没有答案