Created
July 23, 2020 02:49
-
-
Save AdamMc331/2f6842fdba8c106776881bb8417eee0d to your computer and use it in GitHub Desktop.
Shows an example of wrapping shared preferences and how we can use a fake to test the value.
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 FakePreferences : Preferences { | |
var storedLongCallCount = 0 | |
private set | |
var getLongCallCount = 0 | |
private set | |
/** | |
* In this fake, we're just incrementing the number of calls to get long, but we could be more | |
* thorough and track the key that was called. | |
*/ | |
override fun getLong(key: String, default: Long): Long { | |
getLongCallCount++ | |
return 0L | |
} | |
override fun storeLong(key: String, value: Long) { | |
storedLongCallCount++ | |
} | |
} |
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
interface Preferences { | |
fun getLong(key: String, default: Long): Long | |
fun storeLong(key: String, value: Long) | |
} | |
class AndroidPreferences(private val preferences: SharedPreferences): Preferences { | |
override fun getLong(key: String, default: Long): Long { | |
return preferences.getLong(key, default) | |
} | |
override fun storeLong(key: String, value: Long) { | |
preferences.edit().putLong(key, value).apply() | |
} | |
} |
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 UserProvider( | |
private val preferences: Preferences | |
) { | |
var userId: Long | |
get() = preferences.getLong("USER_ID", 0L) | |
set(value) { | |
preferences.storeLong("USER_ID", value) | |
} | |
} |
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 UserProviderTest { | |
fun testStoredId() { | |
val fakePreferences = FakePreferences() | |
val userProvider = UserProvider(fakePreferences) | |
userProvider.userId = 123L | |
assertThat(fakePreferences.storedLongCallCount).isEqualTo(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment