Created
January 12, 2023 12:07
-
-
Save ziglee/5270e6fefba92bb201f3f3d43db76419 to your computer and use it in GitHub Desktop.
"multiple instances" error when removing value during unit testing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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