Skip to content

Instantly share code, notes, and snippets.

@ziglee
Created January 12, 2023 12:07
Show Gist options
  • Save ziglee/5270e6fefba92bb201f3f3d43db76419 to your computer and use it in GitHub Desktop.
Save ziglee/5270e6fefba92bb201f3f3d43db76419 to your computer and use it in GitHub Desktop.
"multiple instances" error when removing value during unit testing
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStoreFile
import androidx.test.core.app.ApplicationProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.SupervisorJob
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@ExperimentalCoroutinesApi
@RunWith(RobolectricTestRunner::class)
class TestDataStore {
companion object {
private val DATASTORE_KEY = stringPreferencesKey("DATASTORE_KEY")
}
@get:Rule
val testCoroutineRule = TestCoroutineRule()
private lateinit var dataStore: DataStore<Preferences>
@Before
fun setup() {
val context = ApplicationProvider.getApplicationContext<Context>()
dataStore =
PreferenceDataStoreFactory.create(
scope = CoroutineScope(testCoroutineRule.testCoroutineDispatcher + SupervisorJob())
) {
context.preferencesDataStoreFile("preferences")
}
}
@Test
fun test() {
testCoroutineRule.runBlockingTest {
dataStore.edit { it[DATASTORE_KEY] = "team" }
dataStore.edit { it.remove(DATASTORE_KEY) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment