ObtainFavoritasAction { public Observable<List<Favorita>> getFavoritas() { return Observable.concat( favoritaLocalDataSource.getFavoritas(), favoritaRemoteDataSource.getFavoritas() .filter((favoritas) -> !favoritas.isEmpty()) .flatMap(favoritaLocalDataSource::replaceFavoritas) .switchIfEmpty(favoritaLocalDataSource.getFavoritas() .flatMap(favoritaRemoteDataSource::replaceFavoritas) .flatMap(__ -> Observable.empty())) ); } ObtainFavoritasAction(FavoritaDataSource favoritaLocalDataSource, FavoritaDataSource favoritaRemoteDataSource); Observable<List<Favorita>> getFavoritas();  }
@Test public void return_favoritas_from_local_first() throws Exception { List<Favorita> localFavs = singletonList(new Favorita()); when(localDataSource.getFavoritas()).thenReturn(just(localFavs)); List<List<Favorita>> results = toList(obtainFavoritasAction.getFavoritas()); assertThat(results.get(0)).isSameAs(localFavs); }
@Test public void return_favoritas_from_remote_second() throws Exception { List<Favorita> localFavs = singletonList(new Favorita()); List<Favorita> remoteFavs = singletonList(new Favorita()); when(localDataSource.getFavoritas()).thenReturn(just(localFavs)); when(remoteDataSource.getFavoritas()).thenReturn(just(remoteFavs)); List<List<Favorita>> results = toList(obtainFavoritasAction.getFavoritas()); assertThat(results.get(1)).isSameAs(remoteFavs); }
@Test public void return_one_result_when_remote_is_empty() throws Exception { List<Favorita> localFavs = singletonList(new Favorita()); when(localDataSource.getFavoritas()).thenReturn(just(localFavs)); when(remoteDataSource.getFavoritas()).thenReturn(empty()); List<List<Favorita>> results = toList(obtainFavoritasAction.getFavoritas()); assertThat(results).hasSize(1); }
@Test public void replace_local_when_remote_returns_content() throws Exception { List<Favorita> remoteFavs = singletonList(new Favorita()); when(remoteDataSource.getFavoritas()).thenReturn(just(remoteFavs)); obtainFavoritasAction.getFavoritas().toBlocking().subscribe(); verify(localDataSource).replaceFavoritas(remoteFavs); }
@Test public void dont_replace_local_when_remote_returns_empty_list() throws Exception { when(remoteDataSource.getFavoritas()).thenReturn(just(emptyList())); obtainFavoritasAction.getFavoritas().toBlocking().subscribe(); verify(localDataSource, never()).replaceFavoritas(anyListOf(Favorita.class)); }
@Test public void replace_remote_with_loca_when_remote_returns_emtpy_list() throws Exception { List<Favorita> localFavs = singletonList(new Favorita()); when(localDataSource.getFavoritas()).thenReturn(just(localFavs)); when(remoteDataSource.getFavoritas()).thenReturn(just(emptyList())); obtainFavoritasAction.getFavoritas().toBlocking().subscribe(); verify(remoteDataSource).replaceFavoritas(localFavs); }