### Question:
SingleLevelCacheRepository extends BaseRepository<M, P> implements Repository<M, P> { @NotNull @Override public Single<M> get(P params) { return cacheDataSource.get(params) .switchIfEmpty(Maybe.defer(() -> networkDataSource.getAndUpdate(params, cacheDataSource))) .map(TimeStampedData::getModel) .toSingle(); } SingleLevelCacheRepository(@NotNull DataSource<M, P> networkDataSource, @NotNull MemoryCacheDataSource<M, P> cacheDataSource); @NotNull @Override Single<M> get(P params); @NotNull @Override Single<M> getLatest(P params); @SuppressWarnings("WeakerAccess") void setCacheValidity(Long newCacheValidity); void invalidateCache();  }### Answer:
@Test public void whenGetWithCacheAvailableThenReturnCache() { TestObserver<String> testObserver = TestObserver.create(); when(cacheDataSource.get(parameter)).thenReturn(Maybe.just(CACHE_DATA)); sut.get(parameter) .subscribe(testObserver); testObserver.assertResult(CACHE_STRING); verify(cacheDataSource).get(parameter); verifyZeroInteractions(networkDataSource); }
@Test public void whenGetWithCacheNotAvailableThenReturnFromNetwork() { TestObserver<String> testObserver = TestObserver.create(); when(cacheDataSource.get(parameter)).thenReturn(Maybe.empty()); when(networkDataSource.getAndUpdate(parameter, cacheDataSource)).thenReturn(Maybe.just(NETWORK_DATA)); sut.get(parameter) .subscribe(testObserver); testObserver.assertResult(NETWORK_STRING); verify(cacheDataSource).get(parameter); verify(cacheDataSource, never()).set(anyDouble(), any()); verify(networkDataSource).getAndUpdate(parameter, cacheDataSource); }
@Test public void whenGetWithNetworkFailureThenHandleIt() { TestObserver<String> testObserver = TestObserver.create(); when(cacheDataSource.get(parameter)).thenReturn(Maybe.empty()); when(networkDataSource.getAndUpdate(parameter, cacheDataSource)).thenReturn(Maybe.error(new Exception("generic network error"))); sut.get(parameter) .subscribe(testObserver); testObserver.assertNotComplete() .assertError(throwable -> throwable instanceof Exception) .assertNoValues(); }