1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.surefire.api.util;
20
21 import java.lang.reflect.Constructor;
22
23 import org.junit.Test;
24
25 import static org.assertj.core.api.Assertions.assertThat;
26
27
28
29
30
31
32
33 public class ReflectionUtilsTest {
34 @Test
35 public void shouldGetConstructor() throws Exception {
36 Constructor<ClassWithParameterizedConstructor> constructor =
37 ReflectionUtils.tryGetConstructor(ClassWithParameterizedConstructor.class, int.class);
38 assertThat(constructor).isNotNull();
39
40 assertThat(constructor.newInstance(10)).isInstanceOf(ClassWithParameterizedConstructor.class);
41 }
42
43 @Test
44 public void shouldNotGetNonExistingConstructor() {
45 assertThat(ReflectionUtils.tryGetConstructor(ClassWithParameterizedConstructor.class, String.class))
46 .isNull();
47 }
48
49 @Test
50 public void shouldReloadClass() throws Exception {
51 ClassLoader cl = Thread.currentThread().getContextClassLoader();
52 assertThat(ReflectionUtils.reloadClass(cl, new B())).isEqualTo(B.class);
53 }
54
55 @Test(expected = RuntimeException.class)
56 public void shouldNotInvokeStaticMethod() {
57 ReflectionUtils.invokeStaticMethod(ReflectionUtilsTest.class, "notCallable", new Class<?>[0], new Object[0]);
58 }
59
60 @Test
61 public void shouldInvokeStaticMethod() {
62 Object o = ReflectionUtils.invokeStaticMethod(
63 ReflectionUtilsTest.class, "callable", new Class<?>[0], new Object[0]);
64 assertThat(o).isEqualTo(3L);
65 }
66
67 @Test
68 public void shouldInvokeMethodChain() {
69 Class<?>[] classes1 = {A.class, A.class};
70 String[] chain = {"current", "pid"};
71 Object o = ReflectionUtils.invokeMethodChain(classes1, chain, null);
72 assertThat(o).isEqualTo(3L);
73
74 Class<?>[] classes2 = {A.class, A.class, B.class};
75 String[] longChain = {"current", "createB", "pid"};
76 o = ReflectionUtils.invokeMethodChain(classes2, longChain, null);
77 assertThat(o).isEqualTo(1L);
78 }
79
80 @Test
81 public void shouldInvokeFallbackOnMethodChain() {
82 Class<?>[] classes1 = {A.class, A.class};
83 String[] chain = {"current", "abc"};
84 Object o = ReflectionUtils.invokeMethodChain(classes1, chain, 5L);
85 assertThat(o).isEqualTo(5L);
86
87 Class<?>[] classes2 = {A.class, B.class, B.class};
88 String[] longChain = {"current", "createB", "abc"};
89 o = ReflectionUtils.invokeMethodChain(classes2, longChain, 6L);
90 assertThat(o).isEqualTo(6L);
91 }
92
93 private static void notCallable() {}
94
95 public static long callable() {
96 return 3L;
97 }
98
99 static class A {
100 public static A current() {
101 return new A();
102 }
103
104 public long pid() {
105 return 3L;
106 }
107
108 public B createB() {
109 return new B();
110 }
111 }
112
113 static class B {
114 public long pid() {
115 return 1L;
116 }
117 }
118
119
120
121
122 public static class ClassWithParameterizedConstructor {
123 public ClassWithParameterizedConstructor(int param) {}
124 }
125 }