1
2
3
4
5
6 package mockit;
7
8 import static org.junit.jupiter.api.Assertions.assertEquals;
9
10 import mockit.integration.junit5.JMockitExtension;
11
12 import org.junit.jupiter.api.Test;
13 import org.junit.jupiter.api.extension.ExtendWith;
14
15
16
17
18 @ExtendWith(JMockitExtension.class)
19 class ReentrantDelegateTest {
20
21
22
23
24 public static class RealClass {
25
26
27
28
29
30
31
32
33
34 protected static int nonRecursiveStaticMethod(int i) {
35 return -i;
36 }
37
38
39
40
41
42
43
44
45
46 public int nonRecursiveMethod(int i) {
47 return -i;
48 }
49 }
50
51
52
53
54
55
56
57 @Test
58 void recursiveDelegateMethodWithoutInvocationParameter(@Mocked RealClass mock) {
59 new Expectations() {
60 {
61 RealClass.nonRecursiveStaticMethod(anyInt);
62 result = new Delegate<Object>() {
63 @Mock
64 int delegate(int i) {
65 if (i > 1) {
66 return i;
67 }
68 return RealClass.nonRecursiveStaticMethod(i + 1);
69 }
70 };
71 }
72 };
73
74 int result = RealClass.nonRecursiveStaticMethod(1);
75 assertEquals(2, result);
76 }
77
78
79
80
81
82
83
84 @Test
85 void recursiveDelegateMethodWithInvocationParameterNotUsedForProceeding(@Injectable final RealClass rc) {
86 new Expectations() {
87 {
88 rc.nonRecursiveMethod(anyInt);
89 result = new Delegate<Object>() {
90 @Mock
91 int delegate(Invocation inv, int i) {
92 if (i > 1) {
93 return i;
94 }
95 RealClass it = inv.getInvokedInstance();
96 return it.nonRecursiveMethod(i + 1);
97 }
98 };
99 }
100 };
101
102 int result = rc.nonRecursiveMethod(1);
103 assertEquals(2, result);
104 }
105
106
107
108
109
110
111
112 @Test
113 void nonRecursiveDelegateMethodWithInvocationParameterUsedForProceeding(@Injectable final RealClass rc) {
114 new Expectations() {
115 {
116 rc.nonRecursiveMethod(anyInt);
117 result = new Delegate<Object>() {
118 @Mock
119 int nonRecursiveMethod(Invocation inv, int i) {
120 if (i > 1) {
121 return i;
122 }
123 return inv.proceed(i + 1);
124 }
125 };
126 }
127 };
128
129 int result = rc.nonRecursiveMethod(1);
130 assertEquals(-2, result);
131 }
132 }