|
| 1 | +package org.baeldung.guava; |
| 2 | + |
| 3 | +import com.google.common.cache.CacheBuilder; |
| 4 | +import com.google.common.cache.CacheLoader; |
| 5 | +import com.google.common.cache.LoadingCache; |
| 6 | +import com.google.common.collect.ImmutableMap; |
| 7 | +import com.google.common.collect.Iterables; |
| 8 | +import org.assertj.core.api.Assertions; |
| 9 | +import org.junit.Test; |
| 10 | + |
| 11 | +import java.util.Map; |
| 12 | +import java.util.concurrent.ExecutionException; |
| 13 | + |
| 14 | +import static com.google.common.collect.Iterables.cycle; |
| 15 | +import static com.google.common.collect.Maps.newHashMap; |
| 16 | +import static org.assertj.core.api.Assertions.assertThat; |
| 17 | + |
| 18 | +public class GuavaCacheLoaderTest { |
| 19 | + int callCount = 0; |
| 20 | + |
| 21 | + @Test |
| 22 | + public void givenAMap_whenAddingValues_thenCanTreatThemAsCache() { |
| 23 | + Map<String, String> cache = newHashMap(); |
| 24 | + cache.put("foo", "cachedValueForFoo"); |
| 25 | + cache.put("bar", "cachedValueForBar"); |
| 26 | + |
| 27 | + assertThat(cache.get("foo")).isEqualTo("cachedValueForFoo"); |
| 28 | + assertThat(cache.get("bar")).isEqualTo("cachedValueForBar"); |
| 29 | + } |
| 30 | + |
| 31 | + @Test |
| 32 | + public void givenCacheLoader_whenGettingItemTwice_shouldOnlyCallOnce() throws ExecutionException { |
| 33 | + |
| 34 | + final LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder() |
| 35 | + .build(new CacheLoader<String, String>() { |
| 36 | + @Override |
| 37 | + public String load(final String s) throws Exception { |
| 38 | + return slowMethod(s); |
| 39 | + } |
| 40 | + }); |
| 41 | + |
| 42 | + String value = loadingCache.get("key"); |
| 43 | + value = loadingCache.get("key"); |
| 44 | + |
| 45 | + assertThat(callCount).isEqualTo(1); |
| 46 | + assertThat(value).isEqualTo("key"); |
| 47 | + } |
| 48 | + |
| 49 | + @Test |
| 50 | + public void givenCacheLoader_whenRefreshingItem_shouldCallAgain() throws ExecutionException { |
| 51 | + |
| 52 | + final LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder() |
| 53 | + .build(new CacheLoader<String, String>() { |
| 54 | + @Override |
| 55 | + public String load(final String s) throws Exception { |
| 56 | + return slowMethod(s); |
| 57 | + } |
| 58 | + }); |
| 59 | + |
| 60 | + String value = loadingCache.get("key"); |
| 61 | + loadingCache.refresh("key"); |
| 62 | + |
| 63 | + assertThat(callCount).isEqualTo(2); |
| 64 | + assertThat(value).isEqualTo("key"); |
| 65 | + } |
| 66 | + |
| 67 | + private String slowMethod(final String s) { |
| 68 | + callCount++; |
| 69 | + return s; |
| 70 | + } |
| 71 | +} |
0 commit comments