From 451f756fe12a32d2a943db80124b522ecbd557af Mon Sep 17 00:00:00 2001 From: Nate Bosch Date: Mon, 10 Jul 2023 03:19:29 -0700 Subject: [PATCH] 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 --- CHANGELOG.md | 1 + README.md | 21 +++++++++++++++++++++ example/example.dart | 20 +++++++++++++++++++- 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20aeb153..5657515f 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 4e7bed00..74fee184 100644 --- a/README.md +++ b/README.md @@ -350,6 +350,27 @@ behavior? 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 77cd00bc..62480f33 100644 --- a/example/example.dart +++ b/example/example.dart @@ -26,8 +26,14 @@ class FakeCat extends Fake implements Cat { } } +abstract class Callbacks { + Cat findCat(String name); + String? makeSound(); +} + @GenerateMocks([ - Cat + Cat, + Callbacks, ], customMocks: [ MockSpec(as: #MockCatRelaxed, returnNullOnMissingStub: true), ]) @@ -206,6 +212,18 @@ void main() { 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();