From b279e709893dd4f4928445b1178c18217ddfdbee Mon Sep 17 00:00:00 2001 From: Andrew Morgan Date: Sun, 12 Feb 2017 18:38:17 +0000 Subject: [PATCH] CacheLoader tests --- .../baeldung/guava/GuavaCacheLoaderTest.java | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 guava/src/test/java/org/baeldung/guava/GuavaCacheLoaderTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCacheLoaderTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCacheLoaderTest.java new file mode 100644 index 0000000000..2aa2e6140b --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/GuavaCacheLoaderTest.java @@ -0,0 +1,71 @@ +package org.baeldung.guava; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import org.assertj.core.api.Assertions; +import org.junit.Test; + +import java.util.Map; +import java.util.concurrent.ExecutionException; + +import static com.google.common.collect.Iterables.cycle; +import static com.google.common.collect.Maps.newHashMap; +import static org.assertj.core.api.Assertions.assertThat; + +public class GuavaCacheLoaderTest { + int callCount = 0; + + @Test + public void givenAMap_whenAddingValues_thenCanTreatThemAsCache() { + Map cache = newHashMap(); + cache.put("foo", "cachedValueForFoo"); + cache.put("bar", "cachedValueForBar"); + + assertThat(cache.get("foo")).isEqualTo("cachedValueForFoo"); + assertThat(cache.get("bar")).isEqualTo("cachedValueForBar"); + } + + @Test + public void givenCacheLoader_whenGettingItemTwice_shouldOnlyCallOnce() throws ExecutionException { + + final LoadingCache loadingCache = CacheBuilder.newBuilder() + .build(new CacheLoader() { + @Override + public String load(final String s) throws Exception { + return slowMethod(s); + } + }); + + String value = loadingCache.get("key"); + value = loadingCache.get("key"); + + assertThat(callCount).isEqualTo(1); + assertThat(value).isEqualTo("key"); + } + + @Test + public void givenCacheLoader_whenRefreshingItem_shouldCallAgain() throws ExecutionException { + + final LoadingCache loadingCache = CacheBuilder.newBuilder() + .build(new CacheLoader() { + @Override + public String load(final String s) throws Exception { + return slowMethod(s); + } + }); + + String value = loadingCache.get("key"); + loadingCache.refresh("key"); + + assertThat(callCount).isEqualTo(2); + assertThat(value).isEqualTo("key"); + } + + private String slowMethod(final String s) { + callCount++; + return s; + } +}