1 package mockit;
2
3 import static org.junit.jupiter.api.Assertions.assertEquals;
4 import static org.junit.jupiter.api.Assertions.fail;
5
6 import org.junit.jupiter.api.BeforeEach;
7 import org.junit.jupiter.api.Test;
8
9
10
11
12 final class FinalMockFieldsTest {
13
14
15
16
17 static final class Collaborator {
18
19
20
21
22 Collaborator() {
23 }
24
25
26
27
28
29
30
31 Collaborator(boolean b) {
32 if (!b) {
33 throw new IllegalArgumentException();
34 }
35 }
36
37
38
39
40
41
42 int getValue() {
43 return -1;
44 }
45
46
47
48
49 void doSomething() {
50 }
51 }
52
53
54
55
56 static final class AnotherCollaborator {
57
58
59
60
61
62
63 int getValue() {
64 return -1;
65 }
66
67
68
69
70 void doSomething() {
71 }
72 }
73
74
75 @Injectable
76 final Collaborator mock = new Collaborator();
77
78
79 @Mocked
80 final AnotherCollaborator mock2 = new AnotherCollaborator();
81
82
83
84
85 @BeforeEach
86 void useMockedTypes() {
87 assertEquals(0, mock.getValue());
88 assertEquals(0, mock2.getValue());
89 assertEquals(0, YetAnotherCollaborator.doSomethingStatic());
90 }
91
92
93
94
95 @Test
96 void recordExpectationsOnInjectableFinalMockField() {
97 new Expectations() {
98 {
99 mock.getValue();
100 result = 12;
101 mock.doSomething();
102 times = 0;
103 }
104 };
105
106 assertEquals(12, mock.getValue());
107 }
108
109
110
111
112 @Test
113 void recordExpectationsOnFinalMockField() {
114 AnotherCollaborator collaborator = new AnotherCollaborator();
115
116 new Expectations() {
117 {
118 mock2.doSomething();
119 times = 1;
120 }
121 };
122
123 collaborator.doSomething();
124 assertEquals(0, collaborator.getValue());
125 }
126
127
128 @Mocked
129 final ProcessBuilder mockProcessBuilder = null;
130
131
132
133
134 @Test
135 void recordExpectationsOnConstructorOfFinalMockField() {
136 new Expectations() {
137 {
138 new ProcessBuilder("test");
139 times = 1;
140 }
141 };
142
143 new ProcessBuilder("test");
144 }
145
146
147
148
149 static final class YetAnotherCollaborator {
150
151
152
153
154
155
156
157 YetAnotherCollaborator(boolean b) {
158 if (!b) {
159 throw new IllegalArgumentException();
160 }
161 }
162
163
164
165
166
167
168 int getValue() {
169 return -1;
170 }
171
172
173
174
175 void doSomething() {
176 }
177
178
179
180
181
182
183 static int doSomethingStatic() {
184 return -2;
185 }
186 }
187
188
189 @Mocked
190 final YetAnotherCollaborator unused = null;
191
192
193
194
195 @Test
196 void recordExpectationsOnStaticMethodAndConstructorOfFinalLocalMockField() {
197 new Expectations() {
198 {
199 new YetAnotherCollaborator(true);
200 result = new RuntimeException();
201 YetAnotherCollaborator.doSomethingStatic();
202 result = 123;
203 }
204 };
205
206 try {
207 new YetAnotherCollaborator(true);
208 fail();
209 } catch (RuntimeException ignore) {
210 }
211
212 assertEquals(123, YetAnotherCollaborator.doSomethingStatic());
213 }
214 }