CacheImpl implements Cache<T> { @Override public T get(String key, Function<String, T> loader) { String cacheKey = cacheKey(key); T cacheValue = cacheStore.get(cacheKey, context); if (cacheValue != null) { ActionLogContext.stat("cache_hit", 1); return cacheValue; } logger.debug("load value, key={}", key); T value = load(loader, key); cacheStore.put(cacheKey, value, duration, context); ActionLogContext.stat("cache_miss", 1); return value; } CacheImpl(String name, Class<T> cacheClass, Duration duration); @Override T get(String key, Function<String, T> loader); Optional<T> get(String key); @Override Map<String, T> getAll(Collection<String> keys, Function<String, T> loader); @Override void put(String key, T value); @Override void putAll(Map<String, T> values); @Override void evict(String key); @Override void evictAll(Collection<String> keys); final String name; final Class<T> cacheClass; final Duration duration; public CacheStore cacheStore; }
@Test void getWhenHit() { var value = cacheItem("value"); when(cacheStore.get("name:key", cache.context)).thenReturn(value); TestCache result = cache.get("key", key -> null); assertThat(result).isSameAs(value); }
@Test void get() { TestCache item = cacheItem("value"); when(cacheStore.get("name:key", cache.context)).thenReturn(item); Optional<TestCache> value = cache.get("key"); assertThat(value).get().isSameAs(item); assertThat(cache.get("notExistedKey")).isEmpty(); }
@Test void loaderReturnsNull() { assertThatThrownBy(() -> cache.get("key", key -> null)) .isInstanceOf(Error.class) .hasMessageContaining("value must not be null"); }