Skip to content

Commit 451f756

Browse files
nateboschcopybara-github
authored andcommitted
Add example of mocking callbacks
Towards #62 Update the README and example usage with an example of writing a class to hold the callback signatures and mocking it with codegen. Demonstrate that the callbacks can be stubbed after being torn off. PiperOrigin-RevId: 546817751
1 parent c13496c commit 451f756

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
## 5.4.3-wip
22

33
* Require analyzer 5.12.0.
4+
* Add example of writing a class to mock function objects.
45

56
## 5.4.2
67

README.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,27 @@ behavior?
350350
non-`null` value for a non-nullable return type). The value should not be used
351351
in any way; it is returned solely to avoid a runtime type exception.
352352

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+
353374
## Writing a fake
354375

355376
You can also write a simple fake class that implements a real class, by

example/example.dart

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,14 @@ class FakeCat extends Fake implements Cat {
2626
}
2727
}
2828

29+
abstract class Callbacks {
30+
Cat findCat(String name);
31+
String? makeSound();
32+
}
33+
2934
@GenerateMocks([
30-
Cat
35+
Cat,
36+
Callbacks,
3137
], customMocks: [
3238
MockSpec<Cat>(as: #MockCatRelaxed, returnNullOnMissingStub: true),
3339
])
@@ -206,6 +212,18 @@ void main() {
206212
await untilCalled(cat.eatFood(any)); // This completes immediately.
207213
});
208214

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+
209227
test('Fake class', () {
210228
// Create a new fake Cat at runtime.
211229
final cat = FakeCat();

0 commit comments

Comments
 (0)