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 1 commit
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
25 changes: 13 additions & 12 deletions packages/mocktail/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,30 +226,31 @@ By default when a class extends `Mock` any unstubbed methods return `null`. When
For example, take the following class and its method:

```dart
class MockPerson extends Mock implements Person {}

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

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

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

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

```dart
when(() => person.doSomething(any<int>())).thenAnswer((_) => 1);
person.doSomething(1);
verify(() => person.doSomething(any<int>())).called(1);
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 `any<T>()`, any explicit type that allows `any<T>()` infer its type will allow the method to be stubbed for that type:
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(() => person.doSomething<int>(any())).thenAnswer((_) => 1);
when(() => cache.set(any(), any<int>())).thenAnswer((_) => true);
alestiago marked this conversation as resolved.
Show resolved Hide resolved
```