TechForumApiImpl implements TechForumApi { @NonNull @Override public List<Talk> retrieveAllTalks(boolean fromCache) throws IOException { final List<Talk> response = new ArrayList<>(); if (fromCache) { List<Talk> cachedResponses = localRepository.getTalkList(); if (cachedResponses == null) { return response; } else { response.addAll(cachedResponses); } } else { Call<List<Session>> talkListCall = remoteRepository.getAllTalks(); Response<List<Session>> talkListResponse = talkListCall.execute(); if (!talkListResponse.isSuccessful()) { throw new IOException("error while loading session list"); } List<Session> talkList = talkListResponse.body(); if (talkList == null) { return response; } for (Session session : talkList) { response.add(Mapper.mapSessionToTalk(session)); } localRepository.setTalkList(response); } return response; } TechForumApiImpl(HttpUrl baseUrl, Context context); @NonNull @Override List<Talk> retrieveAllTalks(boolean fromCache); @NonNull @Override List<Talk> retrieveFavoriteTalks(); @Override void addTalkToFavorites(Talk talk); @Override void removeTalkFromFavorites(Talk talk); @Override boolean isTalkFavorite(Talk talk);  }
@Test public void should_retrieve_talks_from_network() throws Exception { mockWebServer.enqueue(new MockResponse().setBody(SAMPLE_SERVER_DATA)); List<Talk> talks = techForumImpl.retrieveAllTalks(false); assertNotNull(talks); assertEquals(1, talks.size()); Talk talk = talks.get(0); assertEquals("123456", talk.getId()); assertEquals("sample title", talk.getTitle()); assertEquals("11:10", talk.getStartAt()); assertEquals("11:55", talk.getEndAt()); assertEquals(2, talk.getAuthors().size()); assertEquals("author1", talk.getAuthors().get(0)); assertEquals("author2", talk.getAuthors().get(1)); }
@Test public void should_access_cached_talks_after_successful_network_request() throws Exception { mockWebServer.enqueue(new MockResponse().setBody(SAMPLE_SERVER_DATA)); List<Talk> talksNotYetCached = techForumImpl.retrieveAllTalks(true); assertNotNull(talksNotYetCached); assertEquals(0, talksNotYetCached.size()); List<Talk> talksFromNetwork = techForumImpl.retrieveAllTalks(false); assertNotNull(talksFromNetwork); assertEquals(1, talksFromNetwork.size()); List<Talk> talksCached = techForumImpl.retrieveAllTalks(true); assertNotNull(talksCached); assertArrayEquals(talksFromNetwork.toArray(), talksCached.toArray()); }