Mock Extension Methods | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5443751-testing-with-mockk/lessons/8

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.