View Javadoc

1   package com.atlassian.cache.compat.memory;
2   
3   
4   import com.atlassian.cache.compat.Cache;
5   import com.atlassian.cache.compat.CacheLoader;
6   import com.atlassian.util.concurrent.NotNull;
7   import org.hamcrest.Matchers;
8   import org.junit.Test;
9   
10  import java.lang.reflect.Field;
11  
12  import static org.hamcrest.Matchers.equalTo;
13  import static org.hamcrest.Matchers.instanceOf;
14  import static org.junit.Assert.assertThat;
15  
16  
17  /**
18   *
19   * @since 1.1
20   */
21  public class MemoryCacheFactoryTest
22  {
23  
24  
25      @Test
26      public void testSimpleCache()
27      {
28          Cache<Long, String> cache = makeSimpleCache();
29          cache.put(4L, "1");
30          assertThat(cache.get(4L), equalTo("1"));
31      }
32  
33      @Test
34      public void testComputingCache()
35      {
36          Cache<Long, String> cache = makeComputingCache();
37          assertThat(cache.get(4L), equalTo("4"));
38      }
39  
40      protected Cache<Long, String> makeSimpleCache()
41      {
42          MemoryCacheFactory factory = new MemoryCacheFactory();
43          Cache<Long, String> cache = factory.getCache("mycache");
44          assertEmpty(cache);
45          return cache;
46      }
47  
48      protected Cache<Long, String> makeComputingCache()
49      {
50          MemoryCacheFactory factory = new MemoryCacheFactory();
51          Cache<Long, String> cache = factory.getCache("mycache", new CacheLoader<Long, String>()
52          {
53              @Override
54              public String load(@NotNull final Long key)
55              {
56                  return key.toString();
57              }
58          });
59          assertEmpty(cache);
60          return cache;
61      }
62  
63      protected static <K,V> void assertEmpty(Cache<K,V> cache)
64      {
65          assertThat(cache.getKeys(), Matchers.<K>empty());
66      }
67  
68      protected void assertCacheInstanceOf(final Cache cache, final Class<?> aClass) throws Exception
69      {
70          Field internalCacheField = cache.getClass().getDeclaredField("internalCache");
71          internalCacheField.setAccessible(true);
72          Object internalCache = internalCacheField.get(cache);
73          assertThat(internalCache, instanceOf(aClass));
74      }
75  }