I am coming into a legacy codebase which uses SharedPreferences for data persistence. I'd like to test saving/retrieving a value, mocking using MockK. However, the assertion in this unit test never passes. It is as if the SharedPrefs aren't stored properly in testing:
class MyProfilePrefsTest {
private lateinit var myProfilePrefs: ProfilePrefs
@RelaxedMockK private lateinit var mockSharedPrefs: SharedPreferences
@RelaxedMockK private lateinit var context: Context
@Before
fun setup() {
MockKAnnotations.init(this)
val sharedPreferences = mockk<SharedPreferences>()
every { sharedPreferences.edit() } returns (mockk())
myProfilePrefs = ProfilePrefs(context, sharedPreferences)
mockStatic(DeviceInfo::class)
every { DeviceInfo.serialNumber() } returns "fake_serial"
}
@Test
fun `Saving correct cellular download pref for device id`() {
// Arrange
val isEnabled = true
// Act
myProfilePrefs.setCellularDownloadingEnabled(isEnabled)
// Assert
assertTrue(myProfilePrefs.getCellularDownloadingEnabled())
}}
Anybody know how to unit test SharedPrefs?
SharedPreferences.Editor
is the problem; since it's a mock, callingcommit()
orapply()
won't actually do anything.Editor
then?