Last active
February 15, 2023 06:46
-
-
Save amalhanaja/6ed546fb14da34621e3b84af332157c5 to your computer and use it in GitHub Desktop.
This file contains 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
dependencies { | |
implementation("androidx.datastore:datastore-preferences:1.0.0") | |
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4") | |
... | |
} |
This file contains 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
val KEY_NAME = stringPreferencesKey("name") | |
class UserRepository( | |
private val dataStore: DataStore<Preferences>, | |
) { | |
val name: Flow<String> = dataStore.data.map { preferences -> | |
preferences[KEY_NAME].orEmpty() | |
} | |
suspend fun setName(name: String) { | |
dataStore.edit { mutablePreferences -> | |
mutablePreferences[KEY_NAME] = name | |
} | |
} | |
} |
This file contains 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
class UserRepositoryTest { | |
@get:Rule | |
val tmpFolder: TemporaryFolder = TemporaryFolder.builder().assureDeletion().build() | |
private val testDispatcher = UnconfinedTestDispatcher() | |
private val testScope = TestScope(testDispatcher + Job()) | |
private val testDataStore: DataStore<Preferences> = PreferenceDataStoreFactory.create( | |
scope = testScope, | |
produceFile = { tmpFolder.newFile("user.preferences_pb") } | |
) | |
private val subject: UserRepository = UserRepository(testDataStore) | |
@Test | |
fun whenGetNameForTheFirstTime_thenReturnDefaultValue() = testScope.runTest { | |
//When | |
val actual = subject.name.first() | |
//Then | |
assertEquals("", actual) | |
} | |
@Test | |
fun whenSetName_thenUpdateName() = testScope.runTest { | |
// When | |
subject.setName("Alfian") | |
//Then | |
assertEquals("Alfian", subject.name.first()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment