1
2
3
4
5
6 package mockit.internal.reflection;
7
8 import static org.junit.jupiter.api.Assertions.assertEquals;
9 import static org.junit.jupiter.api.Assertions.assertNull;
10 import static org.junit.jupiter.api.Assertions.assertThrows;
11
12 import java.lang.reflect.Method;
13
14 import org.junit.jupiter.api.Test;
15
16 final class MethodReflectionTest {
17
18 static class SampleClass {
19 public String publicMethod(String s) {
20 return "public-" + s;
21 }
22
23 public String throwingMethod(String msg) {
24 throw new RuntimeException(msg);
25 }
26
27 public String throwingCheckedException() throws Exception {
28 throw new Exception("checked");
29 }
30
31 private static String privateStatic() {
32 return "static-result";
33 }
34
35 public int add(int a, int b) {
36 return a + b;
37 }
38 }
39
40 @Test
41 void invokePublicIfAvailableWhenMethodExists() {
42 SampleClass obj = new SampleClass();
43 String result = MethodReflection.invokePublicIfAvailable(SampleClass.class, obj, "publicMethod",
44 new Class<?>[] { String.class }, "test");
45 assertEquals("public-test", result);
46 }
47
48 @Test
49 void invokePublicIfAvailableWhenMethodNotFound() {
50 SampleClass obj = new SampleClass();
51 Object result = MethodReflection.invokePublicIfAvailable(SampleClass.class, obj, "nonExistentMethod",
52 new Class<?>[] { String.class }, "test");
53 assertNull(result);
54 }
55
56 @Test
57 void invokeWithCheckedThrowsInvokesMethod() throws Throwable {
58 SampleClass obj = new SampleClass();
59 String result = MethodReflection.invokeWithCheckedThrows(SampleClass.class, obj, "publicMethod",
60 new Class<?>[] { String.class }, "hello");
61 assertEquals("public-hello", result);
62 }
63
64 @Test
65 void invokeWithCheckedThrowsRethrowsCause() {
66 SampleClass obj = new SampleClass();
67 assertThrows(Exception.class, () -> MethodReflection.invokeWithCheckedThrows(SampleClass.class, obj,
68 "throwingCheckedException", new Class<?>[0]));
69 }
70
71 @Test
72 void invokeMethodOnInstanceViaMethod() throws NoSuchMethodException {
73 SampleClass obj = new SampleClass();
74 Method method = SampleClass.class.getMethod("publicMethod", String.class);
75 String result = MethodReflection.invoke(obj, method, "world");
76 assertEquals("public-world", result);
77 }
78
79 @Test
80 void invokeThrowingRuntimeExceptionRethrowsIt() throws NoSuchMethodException {
81 SampleClass obj = new SampleClass();
82 Method method = SampleClass.class.getMethod("throwingMethod", String.class);
83 RuntimeException ex = assertThrows(RuntimeException.class, () -> MethodReflection.invoke(obj, method, "boom"));
84 assertEquals("boom", ex.getMessage());
85 }
86
87 @Test
88 void findCompatibleMethodUsedByDeencapsulation() {
89 Method method = MethodReflection.findCompatibleMethod(SampleClass.class, "publicMethod",
90 new Class<?>[] { String.class });
91 assertEquals("publicMethod", method.getName());
92 }
93 }