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