Skip to content

Commit

Permalink
Add example of mocking callbacks
Browse files Browse the repository at this point in the history
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
  • Loading branch information
natebosch authored and copybara-github committed Jul 10, 2023
1 parent c13496c commit 451f756
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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

Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 19 additions & 1 deletion example/example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<Cat>(as: #MockCatRelaxed, returnNullOnMissingStub: true),
])
Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit 451f756

Please sign in to comment.