Issue
I just added DataStore to our codebase. After that, I found that all sequential UI tests are failing - the first one in a test case pass but next fails with There are multiple DataStores active for the same file
.
I provide a data store instance using Hilt
@InstallIn(SingletonComponent::class)
@Module
internal object DataStoreModule {
@Singleton
@Provides
internal fun provideConfigurationDataStore(
@ApplicationContext context: Context,
configurationLocalSerializer: ClientConfigurationLocalSerializer
): DataStore<ClientConfigurationLocal> = DataStoreFactory.create(
serializer = configurationLocalSerializer,
produceFile = { context.dataStoreFile("configuration.pb") }
)
}
I guess this is happening because In a Hilt test, the singleton component’s lifetime is scoped to the lifetime of a test case rather than the lifetime of the Application.
Any ideas on how to workaround this?
Solution
I had the same issue. One solution I tried but which didn't work (correctly) is to make sure the tests, once done, remove the dataStore files (the whole folder) and close the scope (the overridden scope that you manage in a "manager" class), like so: https://github.com/wwt/testing-android-datastore/blob/main/app/src/androidTest/java/com/wwt/sharedprefs/DataStoreTest.kt
I had this in a finished()
block of a TestWatcher
used for these UI tests. For some reason, this was not enough so I ended up not looking deeper into why.
Instead I just used a simpler solution: the UI tests would use their own Dagger component, which has its own StorageModule
module, which provides its own IStorage
implementation, which for UI tests is backed just by an in-memory map, whereas on a production Dagger module would back it up via a DataStore:
interface IStorage {
suspend fun retrieve(key: String): String?
suspend fun store(key: String, data: String)
suspend fun remove(key: String)
suspend fun clear()
I prefer this approach in my case as I don't need to test the actual disk-persistance of this storage in UI tests, but if I had needed it, I'd investigate further into how to reliably ensure the datastore folder and scope are cleaned up before/after each UI test.
Answered By - oblakr24
Answer Checked By - Cary Denson (JavaFixing Admin)