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
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 20aeb15..5657515 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,7 @@
## 5.4.3-wip
* Require analyzer 5.12.0.
+* Add example of writing a class to mock function objects.
## 5.4.2
diff --git a/README.md b/README.md
index 4e7bed0..74fee18 100644
--- a/README.md
+++ b/README.md
@@ -350,6 +350,27 @@
non-`null` value for a non-nullable return type). The value should not be used
in any way; it is returned solely to avoid a runtime type exception.
+## Mocking a Function type
+
+To create mocks for Function objects, write an `abstract class` with a method
+for each function type signature that needs to be mocked. The methods can be
+torn off and individually stubbed and verified.
+
+```dart
+@GenerateMocks([Cat, Callbacks])
+import 'cat_test.mocks.dart'
+
+abstract class Callbacks {
+ Cat findCat(String name);
+}
+
+void main() {
+ var mockCat = MockCat();
+ var findCatCallback = MockCallbacks().findCat;
+ when(findCatCallback('Pete')).thenReturn(mockCat);
+}
+```
+
## Writing a fake
You can also write a simple fake class that implements a real class, by
diff --git a/example/example.dart b/example/example.dart
index 77cd00b..62480f3 100644
--- a/example/example.dart
+++ b/example/example.dart
@@ -26,8 +26,14 @@
}
}
+abstract class Callbacks {
+ Cat findCat(String name);
+ String? makeSound();
+}
+
@GenerateMocks([
- Cat
+ Cat,
+ Callbacks,
], customMocks: [
MockSpec<Cat>(as: #MockCatRelaxed, returnNullOnMissingStub: true),
])
@@ -206,6 +212,18 @@
await untilCalled(cat.eatFood(any)); // This completes immediately.
});
+ test('Mocked callbacks', () {
+ final makeSoundCallback = MockCallbacks().makeSound;
+ when(makeSoundCallback()).thenReturn('woof');
+ expect(makeSoundCallback(), 'woof');
+
+ final findCatCallback = MockCallbacks().findCat;
+ final mockCat = MockCat();
+ when(findCatCallback('Pete')).thenReturn(mockCat);
+ when(mockCat.sound()).thenReturn('meow');
+ expect(findCatCallback('Pete').sound(), 'meow');
+ });
+
test('Fake class', () {
// Create a new fake Cat at runtime.
final cat = FakeCat();