Cache { @Nonnull public V get(@Nonnull K key) { synchronized (cached) { final V value = cached.get(key); if (value != null) { return value; } final V newValue = provider.load(key); cached.put(key, newValue); return newValue; } } Cache(@Nonnull  CacheProvider<K, V> provider); @Nonnull V get(@Nonnull K key);  }
@Test public void whenCacheIsCalled_valueIsReturned() throws Exception { when(provider.load("key1")).thenReturn("value1"); assert_().that(cache.get("key1")).isEqualTo("value1"); }
@Test public void whenCacheIsCalledTwice_providerIsExecutedOnce() throws Exception { when(provider.load("key1")).thenReturn("value1"); cache.get("key1"); cache.get("key1"); verify(provider, times(1)).load("key1"); }
@Test public void valuesForDifferentKeys_areReturnedCorrectly() throws Exception { when(provider.load("key1")).thenReturn("value1"); when(provider.load("key2")).thenReturn("value2"); assert_().that(cache.get("key1")).isEqualTo("value1"); assert_().that(cache.get("key2")).isEqualTo("value2"); }