### Question:
CacheManager { JSONObject retrieveFromCache(String cacheKey) { String filename = cacheKey + ".json"; Path cachedPath = cache.resolve(filename); try { FileTime lastModifiedTime = Files.getLastModifiedTime(cachedPath); Duration between = Duration.between(lastModifiedTime.toInstant(), clock.instant()); long betweenHours = between.toHours(); if (betweenHours > 0L) { if (verbose) { System.out.println("Cache entry expired"); } return null; } JSONTokener tokener = new JSONTokener(newInputStream(cachedPath)); return new JSONObject(tokener); } catch (NoSuchFileException e) { return null; } catch (RuntimeException e) { if (verbose) { System.err.println( "Cache ignored invalid file " + filename + "."); e.printStackTrace(); } return null; } catch (IOException e) { if (verbose) { System.err.println( "Cache ignored file " + filename + " because it cannot be read."); e.printStackTrace(); } return null; } } CacheManager(Path cache, boolean verbose);   CacheManager(Path cache, boolean verbose, Clock clock);   }### Answer:
@Test public void cacheReturnsNullWhenCachedFileIsNotJson() throws Exception { CacheManager manager = cacheManagerWithNonJsonFileForKey("the-cache-key"); JSONObject jsonObject = manager.retrieveFromCache("the-cache-key"); assertThat(jsonObject).isNull(); }
@Test public void messageAboutInvalidCacheFileIsWrittenToSystemErr() throws Exception { CacheManager manager = cacheManagerWithNonJsonFileForKey("the-cache-key"); String out = tapSystemErrNormalized( () -> manager.retrieveFromCache("the-cache-key")); assertThat(out).startsWith( "Cache ignored invalid file the-cache-key.json.\n" + "org.json.JSONException: A JSONObject text must begin with '{' at 3 [character 4 line 1]"); }
@Test public void cacheReturnsNullWhenCachedFileCannotBeRead() throws Exception { skipOnWindows(); CacheManager manager = cacheManagerWithNonReadableJsonFileForKey("the-cache-key"); JSONObject jsonObject = manager.retrieveFromCache("the-cache-key"); assertThat(jsonObject).isNull(); }
@Test public void cacheManagerWithNonReadableJsonFileForKey() throws Exception { skipOnWindows(); CacheManager manager = cacheManagerWithNonReadableJsonFileForKey("the-cache-key"); String out = tapSystemErrNormalized( () -> manager.retrieveFromCache("the-cache-key")); assertThat(out).startsWith( "Cache ignored file the-cache-key.json because it cannot be read.\n" + "java.nio.file.AccessDeniedException:"); }