Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: include generics FAQ #186

Merged
merged 7 commits into from
Feb 10, 2023
Merged
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 38 additions & 0 deletions packages/mocktail/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,41 @@ To address this, we must explicitly stub `sleep` like:
final person = MockPerson();
when(() => person.sleep()).thenAnswer((_) async {});
```

#### Why is my method throwing a `TypeError` when stubbing using `any()`?

[Relevant Issue](https://github.com/felangel/mocktail/issues/162)

By default when a class extends `Mock` any unstubbed methods return `null`. When stubbing using `any()` the type must be inferable. However, when a method has a generic type argument it might not be able to infer the type and as a result, the generic would fallback to `dynamic` causing the method to act as if it was unstubbed.

For example, take the following class and its method:

```dart
class Cache {
bool set<T>(String key, T value) {
return true;
}
}
```

The following stub will be equivalent to calling `set<dynamic>(...)`:

```dart
// The type `T` of `any<T>()` is inferred to be `dynamic`.
when(() => cache.set(any(), any())).thenAnswer((_) => true);
alestiago marked this conversation as resolved.
Show resolved Hide resolved
```

To address this, we must explicitly stub `set` with a type:

```dart
final cache = MockCache();
when(() => cache.set<int>(any(), any())).thenAnswer((_) => true);
alestiago marked this conversation as resolved.
Show resolved Hide resolved
cache.set<int>('key', 1);
verify(() => cache.set<int>(any(), any())).called(1);
```

The type doesn't need to be applied to `set<T>()`, any explicit type that allows `any<T>()` infer its type will allow the method to be stubbed for that type:

```dart
when(() => cache.set(any(), any<int>())).thenAnswer((_) => true);
alestiago marked this conversation as resolved.
Show resolved Hide resolved
```