1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.mapping;
17
18 import static com.googlecode.catchexception.apis.BDDCatchException.caughtException;
19 import static com.googlecode.catchexception.apis.BDDCatchException.when;
20 import static org.assertj.core.api.BDDAssertions.then;
21
22 import java.lang.reflect.Field;
23
24 import org.apache.ibatis.builder.InitializingObject;
25 import org.apache.ibatis.cache.Cache;
26 import org.apache.ibatis.cache.CacheException;
27 import org.apache.ibatis.cache.impl.PerpetualCache;
28 import org.assertj.core.api.Assertions;
29 import org.junit.jupiter.api.Test;
30
31 class CacheBuilderTest {
32
33 @Test
34 void testInitializing() {
35 InitializingCache cache = unwrap(new CacheBuilder("test").implementation(InitializingCache.class).build());
36
37 Assertions.assertThat(cache.initialized).isTrue();
38 }
39
40 @Test
41 void testInitializingFailure() {
42 when(() -> new CacheBuilder("test").implementation(InitializingFailureCache.class).build());
43 then(caughtException()).isInstanceOf(CacheException.class).hasMessage(
44 "Failed cache initialization for 'test' on 'org.apache.ibatis.mapping.CacheBuilderTest$InitializingFailureCache'");
45 }
46
47 @SuppressWarnings("unchecked")
48 private <T> T unwrap(Cache cache) {
49 Field field;
50 try {
51 field = cache.getClass().getDeclaredField("delegate");
52 } catch (NoSuchFieldException e) {
53 throw new IllegalStateException(e);
54 }
55 try {
56 field.setAccessible(true);
57 return (T) field.get(cache);
58 } catch (IllegalAccessException e) {
59 throw new IllegalStateException(e);
60 } finally {
61 field.setAccessible(false);
62 }
63 }
64
65 private static class InitializingCache extends PerpetualCache implements InitializingObject {
66
67 private boolean initialized;
68
69 public InitializingCache(String id) {
70 super(id);
71 }
72
73 @Override
74 public void initialize() {
75 this.initialized = true;
76 }
77
78 }
79
80 private static class InitializingFailureCache extends PerpetualCache implements InitializingObject {
81
82 public InitializingFailureCache(String id) {
83 super(id);
84 }
85
86 @Override
87 public void initialize() {
88 throw new IllegalStateException("error");
89 }
90
91 }
92
93 }