stub_gen
stub_gen is a Dart package that generates stubs using the build package. This can facilitate writing unit tests for model logic.
Features
- Creates a
.stub.dartfile where the stub method is written. - Compatible with classes annotated with
freezed. - Allows insertion of arbitrary values into specific members via named parameters.
- Supports faker annotations by
fakerpackage.
Installation
Add the following to your pubspec.yaml:
stub_gen:
git:
url: https://github.com/fummicc1/stub_gen
ref: 0.0.7
Usage
- Create a model class annotated with
StubGen:
// sample.dart
part 'sample.stub.dart';
@StubGen()
class User {
final String name;
final int age;
final double height;
final String email;
const User(
this.name,
this.age,
this.height,
@EmailAddress()
this.email,
);
String get initial {
return name[0].toUpperCase();
}
bool get isValidEmail {
return email.contains("@");
}
}
StubGenhas adefaultValuesparameter that allows you to modify the default values ofStubbableTypes.- There are some annotations for faker such as
@EmailAddressand@PhoneNumber.
- Run
build_runnerto generate the stub code:
dart run build_runner build
this command generates sample.stub.dart file like below.
// coverage:ignore-file
// ignore_for_file: type=lint
part of 'sample.dart';
// **************************************************************************
// StubGenerator
// **************************************************************************
extension UserStubBuilder on User {
static User build(
{String name = "stub",
int age = 10,
double height = 1.0,
String email = "beahan-madie@sauer.co.uk"}) =>
User(name ?? "stub", age ?? 10, height ?? 1.0, email ?? "stub");
}
- Write a unit test:
import 'package:example/sample.dart';
import 'package:test/test.dart';
void main() {
test("Initial should be capitalized and email should be valid", () {
final user = UserStubBuilder.build(name: 'fummicc1');
expect(user.initial, "F");
expect(user.isValidEmail, isTrue);
});
}