Mock Extension Methods |

This is a companion discussion topic for the original entry at

Hi, How can we test shared preferences? More than call to some methods, is how can I test real content. as isolated test.

Hi @aliceresponde,

So in my apps I typically create a wrapper object around shared preferences that I inject. That class might look something like this:

class Wrapper {
    private val preferences: SharedPreferences = ...
    val isUserLoggedIn: Boolean
        get() = preferences.getBoolean("LOGGED_IN", false)

Then you’d pass an instance of that class into whatever class would use shared preferences. Now it’s easy to mock and you can assert against some preference being updated. Also, you won’t need to use roboelectric or any other third party tool in your unit tests since you’ll be mocking out the android shared preferences dependency.