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  import static org.junit.jupiter.api.Assertions.assertThrows;
22  
23  import org.apache.ibatis.cache.decorators.SerializedCache;
24  import org.apache.ibatis.cache.decorators.SynchronizedCache;
25  import org.apache.ibatis.cache.impl.PerpetualCache;
26  import org.junit.jupiter.api.Test;
27  
28  class PerpetualCacheTest {
29  
30    @Test
31    void shouldDemonstrateHowAllObjectsAreKept() {
32      Cache cache = new PerpetualCache("default");
33      cache = new SynchronizedCache(cache);
34      for (int i = 0; i < 100000; i++) {
35        cache.putObject(i, i);
36        assertEquals(i, cache.getObject(i));
37      }
38      assertEquals(100000, cache.getSize());
39    }
40  
41    @Test
42    void shouldDemonstrateCopiesAreEqual() {
43      Cache cache = new PerpetualCache("default");
44      cache = new SerializedCache(cache);
45      for (int i = 0; i < 1000; i++) {
46        cache.putObject(i, i);
47        assertEquals(i, cache.getObject(i));
48      }
49    }
50  
51    @Test
52    void shouldRemoveItemOnDemand() {
53      Cache cache = new PerpetualCache("default");
54      cache = new SynchronizedCache(cache);
55      cache.putObject(0, 0);
56      assertNotNull(cache.getObject(0));
57      cache.removeObject(0);
58      assertNull(cache.getObject(0));
59    }
60  
61    @Test
62    void shouldFlushAllItemsOnDemand() {
63      Cache cache = new PerpetualCache("default");
64      cache = new SynchronizedCache(cache);
65      for (int i = 0; i < 5; i++) {
66        cache.putObject(i, i);
67      }
68      assertNotNull(cache.getObject(0));
69      assertNotNull(cache.getObject(4));
70      cache.clear();
71      assertNull(cache.getObject(0));
72      assertNull(cache.getObject(4));
73    }
74  
75    @Test
76    void shouldDemonstrateIdIsNull() {
77      Cache cache = new PerpetualCache(null);
78      assertThrows(CacheException.class, () -> cache.hashCode());
79      assertThrows(CacheException.class, () -> cache.equals(new Object()));
80    }
81  }