File tree 3 files changed +41
-1
lines changed
3 files changed +41
-1
lines changed Original file line number Diff line number Diff line change 1
1
## 5.4.3-wip
2
2
3
3
* Require analyzer 5.12.0.
4
+ * Add example of writing a class to mock function objects.
4
5
5
6
## 5.4.2
6
7
Original file line number Diff line number Diff line change @@ -350,6 +350,27 @@ behavior?
350
350
non-` null ` value for a non-nullable return type). The value should not be used
351
351
in any way; it is returned solely to avoid a runtime type exception.
352
352
353
+ ## Mocking a Function type
354
+
355
+ To create mocks for Function objects, write an ` abstract class ` with a method
356
+ for each function type signature that needs to be mocked. The methods can be
357
+ torn off and individually stubbed and verified.
358
+
359
+ ``` dart
360
+ @GenerateMocks([Cat, Callbacks])
361
+ import 'cat_test.mocks.dart'
362
+
363
+ abstract class Callbacks {
364
+ Cat findCat(String name);
365
+ }
366
+
367
+ void main() {
368
+ var mockCat = MockCat();
369
+ var findCatCallback = MockCallbacks().findCat;
370
+ when(findCatCallback('Pete')).thenReturn(mockCat);
371
+ }
372
+ ```
373
+
353
374
## Writing a fake
354
375
355
376
You can also write a simple fake class that implements a real class, by
Original file line number Diff line number Diff line change @@ -26,8 +26,14 @@ class FakeCat extends Fake implements Cat {
26
26
}
27
27
}
28
28
29
+ abstract class Callbacks {
30
+ Cat findCat (String name);
31
+ String ? makeSound ();
32
+ }
33
+
29
34
@GenerateMocks ([
30
- Cat
35
+ Cat ,
36
+ Callbacks ,
31
37
], customMocks: [
32
38
MockSpec <Cat >(as : #MockCatRelaxed , returnNullOnMissingStub: true ),
33
39
])
@@ -206,6 +212,18 @@ void main() {
206
212
await untilCalled (cat.eatFood (any)); // This completes immediately.
207
213
});
208
214
215
+ test ('Mocked callbacks' , () {
216
+ final makeSoundCallback = MockCallbacks ().makeSound;
217
+ when (makeSoundCallback ()).thenReturn ('woof' );
218
+ expect (makeSoundCallback (), 'woof' );
219
+
220
+ final findCatCallback = MockCallbacks ().findCat;
221
+ final mockCat = MockCat ();
222
+ when (findCatCallback ('Pete' )).thenReturn (mockCat);
223
+ when (mockCat.sound ()).thenReturn ('meow' );
224
+ expect (findCatCallback ('Pete' ).sound (), 'meow' );
225
+ });
226
+
209
227
test ('Fake class' , () {
210
228
// Create a new fake Cat at runtime.
211
229
final cat = FakeCat ();
You can’t perform that action at this time.
0 commit comments