SpringBasedExpiringValueCache implements ExpiringValueCache<K, V> { @Override public V get(final K key) { if (key == null) { return null; } else { @SuppressWarnings("unchecked") final ExpiringValue<V> value = cache.get(key, ExpiringValue.class); if (value == null) { LOG.trace("cache miss [key: {}]", key); return null; } else if (value.isExpired()) { LOG.trace("cache hit expired [key: {}]", key); cache.evict(key); return null; } else { LOG.trace("cache hit [key: {}]", key); return value.getValue(); } } } SpringBasedExpiringValueCache(final Cache cache); @Override void put(final K key, final V value, final Instant expirationTime); @Override void put(final K key, final V value, final Duration maxAge); @Override V get(final K key);  }
@SuppressWarnings("unchecked") @Test public void testGetResponseFromCache() { final ExpiringValue<String> value = mock(ExpiringValue.class); when(value.isExpired()).thenReturn(Boolean.FALSE); when(value.getValue()).thenReturn("hello"); when(springCache.get("key", ExpiringValue.class)).thenReturn(value); final String result = cache.get("key"); assertThat(result).isEqualTo("hello"); verify(springCache, never()).evict("key"); }
@SuppressWarnings("unchecked") @Test public void testGetResponseFromCacheEvictsExpiredValue() { final ExpiringValue<String> value = mock(ExpiringValue.class); when(value.isExpired()).thenReturn(Boolean.TRUE); when(springCache.get("key", ExpiringValue.class)).thenReturn(value); final String result = cache.get("key"); assertThat(result).isNull(); verify(springCache).evict("key"); }