View Javadoc
1   /*
2    *    Copyright 2009-2023 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
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  }