5

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?

3
  • 2
    I assume that the mocked SharedPreferences.Editor is the problem; since it's a mock, calling commit() or apply() won't actually do anything.
    – Ben P.
    Jul 22, 2019 at 17:34
  • Is it necessary to mock Editor then? Jul 22, 2019 at 17:36
  • I don't have experience writing unit tests for SharedPreferences. I would generally expect that you instead use instrumented tests with a real prefs store (that you set up and tear down as appropriate), but even there I don't have real experience actually doing it.
    – Ben P.
    Jul 22, 2019 at 17:40

2 Answers 2

8

You need Robolectric library to test classes related to the Context. This library will simulate an Android device(without emulator).
In that case, you can use RuntimeEnvironment.application.getApplicationContext() which will return real, not mocked object of Context class.

update as of May 2020:

RuntimeEnvironment.application.getApplicationContext() is now Deprecated.

please use ApplicationProvider.getApplicationContext() to get the Context. also, keep in mind that you should add testImplementation 'androidx.test:core:1.2.0' to your build.gradle.

so Espresso can help you as well, but it is instrumental tests though.

2
  • I though Robolectric is now AndroidX Test? Jul 22, 2019 at 18:16
  • 1
    If you need to use some internal android classes like SharedPrefernces, you need to use the context of Robolectric.
    – samaromku
    Jul 23, 2019 at 11:31
7

Thanks to @samaromku's suggested answer above. Here is the full solution. It uses AndroidX Test runner:

@RunWith(AndroidJUnit4::class)
class ProfilePrefsTest {
  private lateinit var profilePrefs: ProfilePrefs
  private lateinit var context: Context

  @Before
  fun setup() {
    context = getApplicationContext<MyApplication>()
    val sharedPreferences = context.getSharedPreferences(
        "prefs",
        MODE_PRIVATE
    );
    profilePrefs = ProfilePrefs(context, sharedPreferences)

    mockStatic(DeviceInfo::class)
    every { DeviceInfo.serialNumber() } returns FAKE_SERIAL_NUMBER
  }

  @Test
  fun `Saving correct cellular download pref for device id`() {
    // Arrange
    val isEnabled = true

    // Act
    profilePrefs.setCellularDownloadingEnabled(isEnabled)

    // Assert
    assertTrue(profilePrefs.isCellularDownloadingEnabled())
}

}

3
  • 12
    simply asking a question here, but isn't testing shared preferences redundant or wrong ? we know that they work, it's an android component, not one of our own, so shouldn't you be testing the logic around using prefs instead of actually testing prefs...? Jul 23, 2019 at 6:37
  • @a_local_nobody yes, one should only test the code/business logic that he/she writes. there's no need to test the framework (Android) components that are already there and proven to work. most of all times, our logic is what makes those components do something wrong, not theirs: wrong data, improper methods calls, etc. You are very right in this case. Testing sharedprefs like this is discouraged and should be avoided at all cost. May 16, 2021 at 22:05
  • 3
    Though! These are the android components but it is your code writing to, it is your code that is retrieving. So if you have ever heard of Test-Driven Development. I would suggest writing a test like so. Being a lazy developer I still feel you are right. :D Jul 18, 2021 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.