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