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 org.apache.ibatis.cache.decorators.FifoCache;
23  import org.apache.ibatis.cache.impl.PerpetualCache;
24  import org.junit.jupiter.api.Test;
25  
26  class FifoCacheTest {
27  
28    @Test
29    void shouldRemoveFirstItemInBeyondFiveEntries() {
30      FifoCache cache = new FifoCache(new PerpetualCache("default"));
31      cache.setSize(5);
32      for (int i = 0; i < 5; i++) {
33        cache.putObject(i, i);
34      }
35      assertEquals(0, cache.getObject(0));
36      cache.putObject(5, 5);
37      assertNull(cache.getObject(0));
38      assertEquals(5, cache.getSize());
39    }
40  
41    @Test
42    void shouldRemoveItemOnDemand() {
43      FifoCache cache = new FifoCache(new PerpetualCache("default"));
44      cache.putObject(0, 0);
45      assertNotNull(cache.getObject(0));
46      cache.removeObject(0);
47      assertNull(cache.getObject(0));
48    }
49  
50    @Test
51    void shouldFlushAllItemsOnDemand() {
52      FifoCache cache = new FifoCache(new PerpetualCache("default"));
53      for (int i = 0; i < 5; i++) {
54        cache.putObject(i, i);
55      }
56      assertNotNull(cache.getObject(0));
57      assertNotNull(cache.getObject(4));
58      cache.clear();
59      assertNull(cache.getObject(0));
60      assertNull(cache.getObject(4));
61    }
62  
63    @Test
64    void shouldRiseConflictInBeyondFiveEntries() {
65      FifoCache cache = new FifoCache(new PerpetualCache("default"));
66      cache.setSize(5);
67      for (int i = 0; i < 5; i++) {
68        cache.putObject(i, i);
69      }
70      cache.removeObject(1);
71      cache.putObject(1, 1);
72      assertNotNull(cache.getObject(0));
73    }
74  
75  }