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