1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.cache;
17
18 import static org.junit.jupiter.api.Assertions.assertEquals;
19 import static org.junit.jupiter.api.Assertions.assertNotNull;
20 import static org.junit.jupiter.api.Assertions.assertNull;
21
22 import java.lang.reflect.Field;
23 import java.util.Map;
24
25 import org.apache.ibatis.cache.decorators.LruCache;
26 import org.apache.ibatis.cache.impl.PerpetualCache;
27 import org.junit.jupiter.api.Test;
28
29 class LruCacheTest {
30
31 @Test
32 void shouldRemoveLeastRecentlyUsedItemInBeyondFiveEntries() {
33 LruCache cache = new LruCache(new PerpetualCache("default"));
34 cache.setSize(5);
35 for (int i = 0; i < 5; i++) {
36 cache.putObject(i, i);
37 }
38 assertEquals(0, cache.getObject(0));
39 cache.putObject(5, 5);
40 assertNull(cache.getObject(1));
41 assertEquals(5, cache.getSize());
42 }
43
44 @Test
45 void shouldRemoveItemOnDemand() {
46 Cache cache = new LruCache(new PerpetualCache("default"));
47 cache.putObject(0, 0);
48 assertNotNull(cache.getObject(0));
49 cache.removeObject(0);
50 assertNull(cache.getObject(0));
51 }
52
53 @Test
54 void shouldFlushAllItemsOnDemand() {
55 Cache cache = new LruCache(new PerpetualCache("default"));
56 for (int i = 0; i < 5; i++) {
57 cache.putObject(i, i);
58 }
59 assertNotNull(cache.getObject(0));
60 assertNotNull(cache.getObject(4));
61 cache.clear();
62 assertNull(cache.getObject(0));
63 assertNull(cache.getObject(4));
64 }
65
66 @Test
67 void shouldCacheSizeEqualsKeyMapSize() throws Exception {
68 LruCache cache = new LruCache(new PerpetualCache("default"));
69 cache.setSize(5);
70 for (int i = 0; i < 5; i++) {
71 cache.putObject(i, i);
72 }
73 cache.removeObject(1);
74 Field keyMap = cache.getClass().getDeclaredField("keyMap");
75 keyMap.setAccessible(true);
76 Map<Object, Object> map = (Map<Object, Object>) keyMap.get(cache);
77 assertEquals(map.size(), cache.getSize());
78 }
79
80 }