1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.cache;
17
18 import org.apache.ibatis.cache.decorators.SerializedCache;
19 import org.apache.ibatis.cache.impl.PerpetualCache;
20 import org.junit.jupiter.api.Test;
21
22 import java.io.Serializable;
23 import java.util.Objects;
24
25 import static org.junit.jupiter.api.Assertions.assertEquals;
26 import static org.junit.jupiter.api.Assertions.assertThrows;
27
28 class SerializedCacheTest {
29
30 @Test
31 void shouldDemonstrateSerializedObjectAreEqual() {
32 SerializedCache cache = new SerializedCache(new PerpetualCache("default"));
33 for (int i = 0; i < 5; i++) {
34 cache.putObject(i, new CachingObject(i));
35 }
36 for (int i = 0; i < 5; i++) {
37 assertEquals(new CachingObject(i), cache.getObject(i));
38 }
39 }
40
41 @Test
42 void shouldDemonstrateNullsAreSerializable() {
43 SerializedCache cache = new SerializedCache(new PerpetualCache("default"));
44 for (int i = 0; i < 5; i++) {
45 cache.putObject(i, null);
46 }
47 for (int i = 0; i < 5; i++) {
48 assertEquals(null, cache.getObject(i));
49 }
50 }
51
52 @Test
53 void throwExceptionWhenTryingToCacheNonSerializableObject() {
54 SerializedCache cache = new SerializedCache(new PerpetualCache("default"));
55 assertThrows(CacheException.class,
56 () -> cache.putObject(0, new CachingObjectWithoutSerializable(0)));
57 }
58
59 static class CachingObject implements Serializable {
60 int x;
61
62 public CachingObject(int x) {
63 this.x = x;
64 }
65
66 @Override
67 public boolean equals(Object o) {
68 if (this == o) return true;
69 if (o == null || getClass() != o.getClass()) return false;
70 CachingObject obj = (CachingObject) o;
71 return x == obj.x;
72 }
73
74 @Override
75 public int hashCode() {
76 return Objects.hash(x);
77 }
78 }
79
80 static class CachingObjectWithoutSerializable {
81 int x;
82
83 public CachingObjectWithoutSerializable(int x) {
84 this.x = x;
85 }
86
87 @Override
88 public boolean equals(Object o) {
89 if (this == o) return true;
90 if (o == null || getClass() != o.getClass()) return false;
91 CachingObjectWithoutSerializable obj = (CachingObjectWithoutSerializable) o;
92 return x == obj.x;
93 }
94
95 @Override
96 public int hashCode() {
97 return Objects.hash(x);
98 }
99 }
100 }