4

I have this Kotlin class that is a wrapper around SharedPreferences in an Android app.

class Preferences(private val context: Context) {
    
    private val preferences: SharedPreferences =
        context.getSharedPreferences("name_of_file", Context.MODE_PRIVATE)
    
    // Integers
    var coins: Int
        get() = preferences.getInt(KEY_COINS, 0)
        set(value) = preferences.edit { putInt(KEY_COINS, value) }
    
    var pressure: Int
        get() = preferences.getInt(KEY_PRESSURE, DEFAULT_PRESSURE)
        set(value) = preferences.edit { putInt(KEY_PRESSURE, value) }
}

I need to mock this class in order to be able to use it in some unit tests for my viewmodels. I tried mocking the get/set methods of the properties but for some reason I'm getting some errors and I need a bit of help.

This is how I try to mock the Preferences class:

private val sharedPreferences = mutableMapOf<String, Any>()
...
val preferences = mockk<Preferences>()
    
    listOf("coins", "pressure").forEach { key ->
        every { preferences getProperty key } returns sharedPreferences[key]
        
        every { preferences setProperty key } answers { // exception on this line
            sharedPreferences[key] = fieldValue
            fieldValue
        }
    }

And I get this exception when running any of the tests that involves this mock

io.mockk.MockKException: Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock

I think the error is quite cryptic. Or, is there any way to mock these fields using mockk?

I have also read the examples from here where I got the inspiration for this solution but seems like there is something I'm missing.

Daniel Bejan
  • 1,468
  • 1
  • 15
  • 39

0 Answers0