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