Testing
Unit Tests
When you are writing unit tests with GetIt in your App you have two possibilities:
- Register all the Objects you need inside your unit Tests so that GetIt can provide its objects to the objects that you are testing.
- Pass your dependent objects into the constructor of your test objects like:
dart
GetIt getIt = GetIt.instance;
class UserManager {
AppModel appModel;
DbService dbService;
UserManager({AppModel? appModel, DbService? dbService}) {
this.appModel = appModel ?? getIt.get<AppModel>();
this.dbService = dbService ?? getIt.get<DbService>();
}
}
This way you don't need to pass them in the AppModel
and dbService
inside your App but you can pass them (or a mocked version) in your Unit tests.
Integration Tests
If you have a mocked version of a Service, you can easily switch between that and the real one based on a flag:
dart
if (testing) {
getIt.registerSingleton<AppModel>(AppModelMock());
} else {
getIt.registerSingleton<AppModel>(AppModelImplementation());
}