Home > Back-end >  How to mock "remove" extension of shared preferences using mockk?
How to mock "remove" extension of shared preferences using mockk?

Time:08-03

Problem Description

I have a method of a data source class that makes the following call to a Shared Preferences extension:

override suspend fun removePendingBatch() {
    preferences.remove(pendingBatchKey)
}

preferences is an instance of enter image description here

CodePudding user response:

I managed to solve this problem by mocking the commit method coming from the SharedPreferences.Editor object by this way:

every { preferences.edit().commit() } returns RandomUtils.nextBoolean()

In this case, just return any boolean, so we can mock the "remove" method, my complete test looks like this:

@Test
fun `when removePendingBatch() is called then remove from preferences`() = runBlockingTest {
    every { preferences.edit().commit() } returns RandomUtils.nextBoolean()
    every { preferences.remove(PENDING_BATCH_KEY) } just runs
    batchDataSource.removePendingBatch()
    verify(exactly = 1) { preferences.remove(PENDING_BATCH_KEY) }
}
  • Related