1 package com.atlassian.cache.ehcache;
2
3 import com.atlassian.cache.Cache;
4 import com.atlassian.cache.CacheLoader;
5 import com.atlassian.cache.ehcache.wrapper.WrapperTestUtils;
6 import net.sf.ehcache.CacheManager;
7 import net.sf.ehcache.config.CacheConfiguration;
8 import net.sf.ehcache.config.Configuration;
9 import net.sf.ehcache.config.MemoryUnit;
10 import org.junit.After;
11 import org.junit.Before;
12 import org.junit.Test;
13 import org.mockito.ArgumentCaptor;
14 import org.mockito.Mockito;
15
16 import javax.annotation.Nonnull;
17
18 import static org.junit.Assert.assertEquals;
19 import static org.junit.Assert.assertSame;
20
21 public class LoadingCacheWrappedValueTest {
22
23 private CacheLoader<Object, Object> testedCacheLoader;
24 private Cache<Object, Object> testedLoadingCache;
25
26 private CacheManager cacheManager;
27 private EhCacheManager ehCacheManager;
28
29 @Before
30 public void init() {
31 Configuration configuration = new Configuration().name(LoadingCacheWrappedValueTest.class.getName());
32 configuration.setDefaultCacheConfiguration(new CacheConfiguration().name("tested").maxBytesLocalHeap(10, MemoryUnit.MEGABYTES));
33 cacheManager = new CacheManager(configuration);
34 ehCacheManager = new EhCacheManager(cacheManager, null, null, WrapperTestUtils.getValueProcessor());
35
36 testedCacheLoader = Mockito.spy(new CacheLoader<Object, Object>() {
37 @Nonnull
38 @Override
39 public Object load(@Nonnull final Object key) {
40 return generateValueFromKey(key);
41 }
42 });
43 testedLoadingCache = ehCacheManager.getCache("tested", testedCacheLoader);
44 }
45
46 @After
47 public void destroy() {
48 cacheManager.shutdown();
49 }
50
51 @Test
52 public void testGetNonExistingValue() {
53 Object key = new Object();
54 Object value = generateValueFromKey(key);
55
56 Object retrievedValue = testedLoadingCache.get(key);
57 assertEquals(value, retrievedValue);
58 }
59
60 @Test
61 public void testLoadParameter() {
62 Object key = new Object();
63
64 ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
65 testedLoadingCache.get(key);
66 Mockito.verify(testedCacheLoader).load(captor.capture());
67 assertSame(key, captor.getValue());
68 }
69
70 private String generateValueFromKey(final Object key) {
71 return "Loaded value: " + key.getClass().getName() + "@" + Integer.toHexString(key.hashCode());
72 }
73 }