https://github.com/digitalrmdy/mockor
Generate Flutter Mockito mocks.
https://github.com/digitalrmdy/mockor
dart flutter mockito mocktail
Last synced: 6 months ago
JSON representation
Generate Flutter Mockito mocks.
- Host: GitHub
- URL: https://github.com/digitalrmdy/mockor
- Owner: digitalrmdy
- License: gpl-3.0
- Created: 2019-11-30T16:38:53.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2024-02-13T15:59:32.000Z (over 1 year ago)
- Last Synced: 2024-11-15T23:37:13.431Z (6 months ago)
- Topics: dart, flutter, mockito, mocktail
- Language: Dart
- Homepage: https://pub.dev/packages/mockor
- Size: 142 KB
- Stars: 5
- Watchers: 5
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# mockor
Generic mocker method generator for [mockito](https://pub.dev/packages/mockito) or [mocktail](https://pub.dev/packages/mocktail).
One `mock` method to mock any class just like in the original [mockito](https://site.mockito.org/).[](https://pub.dev/packages/mockor).
## Getting Started
### Add the dependencies
```yaml
dev_dependencies:
mockor: ^1.0.0```
### Add a `mocker.dart` file in your test folder and a mock method with a `@GenerateMocker` annotation. Don't forget to import [mockito](https://pub.dev/packages/mockito) here.
```dart
// This import is used by the generated mockor file to add Mockito's `@GenerateMocks` annotation.
// This need to be added manually.
import 'package:mockito/mockor.dart';// .mocks.dart will be generated by Mockito which contain all the generated mocks.
// This needs to be added manually.
import 'example.mocks.dart';import 'package:mockor/mockor.dart';
part 'example.mockor.dart';
abstract class ExampleUseCase {
int example(int i);
}abstract class ExampleUseCase2 {
void example2();
}@GenerateMocker([
ExampleUseCase,
ExampleUseCase2,
])
T mock({bool relaxed = false}) => _$mock(relaxed: relaxed);
```### To use the generated mocks, simply import and call the defined mock function
```dart
import '../../mocker.dart';void main() {
late ExampleUseCase exampleUseCase;
late ExampleUseCase2 exampleUseCase2;setUp(() {
// this will return [MockExampleUseCase]
exampleUseCase = mock();
exampleUseCase2 = mock();
});
}
```for more info check out the [example](https://github.com/digitalrmdy/mockito-builder/tree/master/example) module.
## Getting Started using [mocktail](https://pub.dev/packages/mocktail)
### Follow steps like before with slight modifications to `mocker.dart` file```dart
// This import will be used for generating the mocks.
// This needs to be added manually.
import 'package:mocktail/mocktail.dart';import 'package:mockor/mockor.dart';
part 'mocker.mockor.dart';
@GenerateMocker.mocktail(
[
ExampleUseCase,
ExampleUseCase2,
],
// optionally generate relaxedVoid parameter which prevents missing stub errors for `void` and `Future`
generateRelaxedVoidParameter: true,
// optionally generate fallback values for non null params to use `any()`
generateMocktailFallbackValues: GenerateMocktailFallbackValues(
[ExampleModel],
// optionally register a mock class for all the non primitive parameters of all the methods in each class of [GenerateMocker.types] automatically.
autoDetect: true,
),
)
T mock({bool relaxed = false, bool? relaxedVoid}) =>
_$_mock(relaxed: relaxed, relaxedVoid: relaxedVoid);//define a global register fallback values method
void registerFallbackValuesAll() {
_$registerFallbackValues();
}
```### Create `flutter_test_config.dart` in the root of your `test` folder.
```dart
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';import 'mocker.dart';
Future testExecutable(FutureOr Function() testMain) async {
// this will be executed before the main function of any test file in the test folder.
setUpAll(() {
registerFallbackValuesAll();
});
await testMain();
}
```## Optional `relaxed` param to return null on missing stub
The `_$mock()` method takes in an optional `bool` parameter named `relaxed`.
If it's `false`, `throwOnMissingStub` is called on the `Mock` object with so that you get exceptions when you try to call a method that is not stubbed.
However if it's `true`, a `TypeError` is thrown when the method has a non null return type.
On nullable return types, null is returned for missing stubs.It is `true` by default for `mocktail`
It is `false` by default for `mockito````dart
T mock({bool relaxed = false}) => _$mock(relaxed: relaxed);final myService = mock(relaxed: true);
when(myService.doSomethingElse()).thenReturn(true);myService.doSomething(); // this will throw an exception
myService.doSomethingElse(); // this will not throw an exception
```For more info check out the example module.
## Main Advantage over vanilla Mockito
### You can always work with the base type
- Renaming the class will not break tests.
- Find usages will not miss anything
- Never have to import/depend on mocks directly
### Optional `relaxed` parameter at runtime
An optional `relaxed` parameter is added to the generated `_$mock` method.
When set to `true`, `null` is returned for missing nullable stubs. And `TypeError` for non null missing stubs.This is further explained above.
## Advantage over vanilla Mocktail
### Fast Code Generation
Even though Mocktail was created to avoid code generation, here code generation is required but only for the one file with the generic mock function.
There's no dependency to generated code in any of your tests. And each mock class is only 1 line long.
### Private Mock classes
The generated mock classes are private so cannot be imported. Simply call the global `mock` method.
This makes it easier for all developers to follow consistent code conventions.
### Generate `registerFallbackValues` function
An annoying drawback of mocktail is that you need to register fallback values if you want to call the `any()` function on them.
With Mockor, you can generate a `registerFallbackValues` function where you can either specify the types manually or let the generator auto detect them.
Check getting started above for more info.
### Optional `relaxed` parameter
An optional `relaxed` parameter is added to the generated `_$mock` method.
When set to `true`, `null` is returned for missing nullable stubs. And `TypeError` for non null missing stubs.This is further explained above.
### Optional `relaxedVoid` parameter (`mocktail` only feature)
An optional `relaxed` parameter is added to the generated `_$mock` method.
When set to `true`, unstubbed `void`- and `Future` methods don't throw errors.
## FAQ
### How can I hide the generated mock classes from auto import?in the root of your project add an `analysis_options.yaml` with following content:
```yaml
analyzer:
exclude:
- '**/*.mocks.dart' # Mockito @GenerateMocks
```## Troubleshooting
### "Error, a mock class for 'MockExampleUseCase' has not been generated yet."The mocker method only supports returning a mock instance for it's base type.
### Error when using `any`: "The argument type 'Null' can't be assigned to the parameter type..."
To be able to use of `any`, you need the mocked type and not the base type.
An `asMock` extension function is generated for this purpose.```dart
extension ExampleUseCaseAsMockExtension on ExampleUseCase {
MockExampleUseCase asMock() => this as MockExampleUseCase;
}
```
Then in your test:
```dart
abstract class ExampleUseCase {
int example(int i);
}
final ExampleUseCase useCase = mock();
// asMock required becuase int i is non null and `any` returns null. the method is overriden with a nullable param in MockExampleUseCase.
when(useCase.asMock().example(any)).thenReturn(1)
```
Please read Mockito's [Null Safety README](https://github.com/dart-lang/mockito/blob/master/NULL_SAFETY_README.md) for more info.