1
2
3
4
5
6 package mockit;
7
8 import static org.junit.jupiter.api.Assertions.assertEquals;
9 import static org.junit.jupiter.api.Assertions.assertNotNull;
10 import static org.junit.jupiter.api.Assertions.assertNull;
11
12 import java.util.Observable;
13 import java.util.concurrent.Callable;
14
15 import mockit.integration.junit5.JMockitExtension;
16
17 import org.junit.jupiter.api.Test;
18 import org.junit.jupiter.api.extension.ExtendWith;
19
20
21
22
23 @ExtendWith(JMockitExtension.class)
24 class CapturingInstancesTest {
25
26
27
28
29 public interface Service1 {
30
31
32
33
34
35 int doSomething();
36 }
37
38
39
40
41 static final class Service1Impl implements Service1 {
42 @Override
43 public int doSomething() {
44 return 1;
45 }
46 }
47
48
49
50
51 public static final class TestedUnit {
52
53
54 private final Service1 service1 = new Service1Impl();
55
56
57 private final Service1 service2 = new Service1() {
58 @Override
59 public int doSomething() {
60 return 2;
61 }
62 };
63
64
65 Observable observable;
66
67
68
69
70
71
72
73
74
75 public int businessOperation(final boolean b) {
76 new Callable() {
77 @Override
78 public Object call() {
79 throw new IllegalStateException();
80 }
81 }.call();
82
83 observable = new Observable() {
84 {
85 if (b) {
86 throw new IllegalArgumentException();
87 }
88 }
89 };
90
91 return service1.doSomething() + service2.doSomething();
92 }
93 }
94
95
96 @Capturing
97 Service1 service;
98
99
100
101
102 @Test
103 void captureServiceInstancesCreatedByTestedConstructor() {
104 TestedUnit unit = new TestedUnit();
105
106 assertEquals(0, unit.service1.doSomething());
107 assertEquals(0, unit.service2.doSomething());
108 }
109
110
111
112
113
114
115
116
117
118
119
120
121 @Test
122 void captureAllInternallyCreatedInstances(@Capturing Observable observable, @Capturing final Callable<?> callable)
123 throws Exception {
124 new Expectations() {
125 {
126 service.doSomething();
127 returns(3, 4);
128 }
129 };
130
131 TestedUnit unit = new TestedUnit();
132 int result = unit.businessOperation(true);
133 assertEquals(4, unit.service1.doSomething());
134 assertEquals(4, unit.service2.doSomething());
135
136 assertNotNull(unit.observable);
137 assertEquals(7, result);
138
139 new Verifications() {
140 {
141 callable.call();
142 }
143 };
144 }
145
146
147
148
149 public interface Service2 {
150
151
152
153
154
155 int doSomething();
156 }
157
158
159
160
161 static class Base {
162
163
164
165
166
167 boolean doSomething() {
168 return false;
169 }
170 }
171
172
173
174
175 static final class Derived extends Base {
176
177
178
179
180
181 Service2 doSomethingElse() {
182 return null;
183 }
184 }
185
186
187
188
189
190
191
192 @Test
193 void captureSubclassAndCascadeFromMethodExclusiveToSubclass(@Capturing Base capturingMock) {
194 Derived d = new Derived();
195 Service2 service2 = d.doSomethingElse();
196
197
198
199 assertNull(service2);
200 }
201 }