View Javadoc
1   /*
2    *    Copyright 2009-2021 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    *       http://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.*;
19  
20  import org.apache.ibatis.cache.decorators.LruCache;
21  import org.apache.ibatis.cache.impl.PerpetualCache;
22  import org.junit.jupiter.api.Test;
23  
24  class LruCacheTest {
25  
26    @Test
27    void shouldRemoveLeastRecentlyUsedItemInBeyondFiveEntries() {
28      LruCache cache = new LruCache(new PerpetualCache("default"));
29      cache.setSize(5);
30      for (int i = 0; i < 5; i++) {
31        cache.putObject(i, i);
32      }
33      assertEquals(0, cache.getObject(0));
34      cache.putObject(5, 5);
35      assertNull(cache.getObject(1));
36      assertEquals(5, cache.getSize());
37    }
38  
39    @Test
40    void shouldRemoveItemOnDemand() {
41      Cache cache = new LruCache(new PerpetualCache("default"));
42      cache.putObject(0, 0);
43      assertNotNull(cache.getObject(0));
44      cache.removeObject(0);
45      assertNull(cache.getObject(0));
46    }
47  
48    @Test
49    void shouldFlushAllItemsOnDemand() {
50      Cache cache = new LruCache(new PerpetualCache("default"));
51      for (int i = 0; i < 5; i++) {
52        cache.putObject(i, i);
53      }
54      assertNotNull(cache.getObject(0));
55      assertNotNull(cache.getObject(4));
56      cache.clear();
57      assertNull(cache.getObject(0));
58      assertNull(cache.getObject(4));
59    }
60  
61  }