ark_di_test 1.0.1
ark_di_test: ^1.0.1 copied to clipboard
Owned test scopes and detached diagnostic matchers for Ark DI.
example/ark_di_test_example.dart
import 'package:ark_di/ark_di.dart';
import 'package:ark_di_test/ark_di_test.dart';
Future<void> main() async {
final DiConfiguration configuration = DiConfiguration(<DiModule>[
const _BooksModule(),
const _SearchModule(),
]);
final DiTestScope scope = await DiTestScope.create(configuration.configure);
final List<String> result = await scope.run<List<String>>(
(final DiResolver resolver) => resolver.get<_Search>().find('dart'),
);
if (result.length != 1 || result.single != 'Dart in practice') {
throw StateError('The isolated graph returned unexpected search results.');
}
if (scope.diagnostics.state != DiContainerState.closed) {
throw StateError('Run must finish cleanup before returning the result.');
}
print(
'Search: ${result.single}; test scope: ${scope.diagnostics.state.name}',
);
}
abstract interface class _Books {
List<String> get titles;
void close();
}
final class _MemoryBooks implements _Books {
bool _closed = false;
@override
List<String> get titles {
if (_closed) {
throw StateError('Repository already closed.');
}
return const <String>['Dart in practice', 'Clean architecture'];
}
@override
void close() {
_closed = true;
}
}
final class _Search {
const _Search(this._books);
final _Books _books;
List<String> find(final String query) {
final String normalized = query.trim().toLowerCase();
if (normalized.isEmpty) {
throw ArgumentError.value(query, 'query', 'Must not be blank');
}
return _books.titles
.where((final String title) => title.toLowerCase().contains(normalized))
.toList(growable: false);
}
}
final class _BooksModule implements DiModule {
const _BooksModule();
@override
void configure(final DiBinder binder) => binder.bindLazySingleton<_Books>(
(_) => _MemoryBooks(),
dispose: (final _Books books) => books.close(),
);
}
final class _SearchModule implements DiModule {
const _SearchModule();
@override
void configure(final DiBinder binder) => binder.bindLazySingleton<_Search>(
(final DiResolver resolver) => _Search(resolver.get<_Books>()),
);
}