如何测试RxSharedPreferences?

时间:2019-05-11 17:53:08

标签: android unit-testing testing mockito sharedpreferences

我的问题是有关如何测试RxSharedPreferences的,因为将值放在userPrefs中不会影响rxPreferences。 userFavoriteStoreIds始终返回空值。在下面,我提供了我要测试的课程,而不是要测试的课程

class StoresRepository(private val prefs: SharedPreferences) {
 init {
    syncStores()
    val rxPreferences = RxSharedPreferences.create(userPrefs)
    userFavoriteStoreIds =  rxPreferences.getString(PREF_USER_FAVORITE_STORES_IDS)
  }


  fun getFavoriteStoreItems(): Flowable<List<DB.Store>> {
    return userFavoriteStoreIds.asObservable()
        .toFlowable(BackpressureStrategy.LATEST)
        .map { favoriteIdsString -> favoriteIdsString.split(";".toRegex()).dropLastWhile { it.isEmpty() } }
        .map { it.map { id -> id.toInt() } }
        .flatMap { favoriteIds ->
          storesDao.getStoresById(favoriteIds)
              .map {
                it.map { store -> store.copy(favorite = true) }
              })
        }
  }


}
Here is my test class

class StoresRepositoryTest {


    @Before
  fun setup() {
    userPrefs = mock()
    userPrefsEditor = mock {}
    `when`(userPrefs.edit()).thenReturn(userPrefsEditor)
    `when`(userPrefsEditor.putString(anyString(), anyString())).thenReturn(userPrefsEditor)
      `when`(userPrefs.getString(anyString(), anyString())).thenReturn("500,1259")

    storesRepository = StoresRepository(userPrefs)
  }

  @Test
  fun test_someXX() {

    Mockito.`when`(storesDao.getStoresById(listOf(2891, 500, 1259))).thenReturn(Flowable.just(asStoresByName()))
    Timber.i(TAG, " " + userPrefs.getString(StoresRepository.PREF_USER_FAVORITE_STORES_IDS,""))
    storesRepository.getFavoriteStoreItems().test()
        .assertValue(asStoresByName())
  }
}




0 个答案:

没有答案