Skip to content

Instantly share code, notes, and snippets.

@AdamMc331
Created July 23, 2020 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdamMc331/2f6842fdba8c106776881bb8417eee0d to your computer and use it in GitHub Desktop.
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.
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++
}
}
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()
}
}
class UserProvider(
private val preferences: Preferences
) {
var userId: Long
get() = preferences.getLong("USER_ID", 0L)
set(value) {
preferences.storeLong("USER_ID", value)
}
}
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