1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.assertThrows;
20
21 import java.io.Serializable;
22 import java.util.Objects;
23
24 import org.apache.ibatis.cache.decorators.SerializedCache;
25 import org.apache.ibatis.cache.impl.PerpetualCache;
26 import org.junit.jupiter.api.Test;
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, () -> cache.putObject(0, new CachingObjectWithoutSerializable(0)));
56 }
57
58 static class CachingObject implements Serializable {
59 private static final long serialVersionUID = 1L;
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) {
69 return true;
70 }
71 if (o == null || getClass() != o.getClass()) {
72 return false;
73 }
74 CachingObject obj = (CachingObject) o;
75 return x == obj.x;
76 }
77
78 @Override
79 public int hashCode() {
80 return Objects.hash(x);
81 }
82 }
83
84 static class CachingObjectWithoutSerializable {
85 int x;
86
87 public CachingObjectWithoutSerializable(int x) {
88 this.x = x;
89 }
90
91 @Override
92 public boolean equals(Object o) {
93 if (this == o) {
94 return true;
95 }
96 if (o == null || getClass() != o.getClass()) {
97 return false;
98 }
99 CachingObjectWithoutSerializable obj = (CachingObjectWithoutSerializable) o;
100 return x == obj.x;
101 }
102
103 @Override
104 public int hashCode() {
105 return Objects.hash(x);
106 }
107 }
108 }