Skip to main content

ark_di_test 1.0.0 copy "ark_di_test: ^1.0.0" to clipboard
ark_di_test: ^1.0.0 copied to clipboard

Owned test scopes and detached diagnostic matchers for Ark DI.

Ark DI Test #

Isolated test scopes and metadata-only matchers for Ark DI. The application uses ark_di; its tests can additionally use ark_di_test as a development dependency. Core has no dependency on this package or on a test runner.

Русская версия

Installation #

dependencies:
  ark_di: ^1.3.0
dev_dependencies:
  ark_di_test: ^1.0.0
  test: ^1.31.2

Requires Ark DI 1.3.0 or a compatible newer 1.x release.

What problem it solves #

A test needs a fresh object graph, explicit fakes and reliable resource cleanup. DiTestScope owns that graph. run waits for cleanup before returning, including when the test body throws. There is no shared container and no global test hook.

One complete test #

import 'package:ark_di/ark_di.dart';
import 'package:ark_di_test/ark_di_test.dart';
import 'package:test/test.dart';

void main() {
  test('reads an isolated dependency and closes the graph', () async {
    final List<int> disposed = <int>[];
    final DiTestScope scope = await DiTestScope.create(
      (final DiBinder binder) =>
          binder.bindInstance<int>(7, dispose: disposed.add),
    );

    await scope.run<void>((final DiResolver resolver) {
      expect(resolver.get<int>(), 7);
      expect(scope.registrations,
          DiTestMatchers.hasRegistration<int>(kind: DiRegistrationKind.instance));
    });

    expect(disposed, <int>[7]);
    expect(scope.diagnostics, DiTestMatchers.hasState(DiContainerState.closed));
  });
}

create waits for rollback if registration fails. run can be called once on an active scope; concurrent or post-close runs are rejected. If preparation after create can throw before run, put that preparation inside the body or register scope.close with your runner's addTearDown immediately. Merely creating a scope does not install automatic cleanup. Do not use run around an entire Flutter widget test: the widget tree can outlive the body callback. Instead register fixture cleanup with the test runner and unmount its users before closing the scope.

Fakes and modules #

Build the graph under test with explicit fake registrations. DiConfiguration accepts a typed list of DiModule objects and its configure method can be passed directly to DiTestScope.create. The runnable search example registers an in-memory repository and a real search service in separate modules.

DiTestScope.child(parent, configure) owns only its new child. The parent remains external. Normal overrideParent: true rules apply; this helper does not mutate or rewire a parent factory. To make a service consume a child fake, register that service in the child too, or build a fresh root containing the tested graph.

Body and cleanup failures #

Result What run does
Body and cleanup succeed Returns the body result after close
Body fails, cleanup succeeds Rethrows the same body error with its original stack
Body succeeds, cleanup fails Throws the close failure
Both fail Rethrows the body error; separately reports DiTestCleanupException

For the last case, supply onCleanupError or let the zone active at the start of run report the secondary failure. The report contains both errors/stacks. Asynchronous reporter failures are observed in that zone. Reporter IO is not awaited and cannot delay delivery of the primary error. run does not cancel arbitrary business futures; it relies on core's existing DI-resolution tracking.

Matchers #

  • hasState accepts DiContainerSnapshot.
  • hasPendingAsyncResolutionCount checks the local tracked call count, not the number of distinct singleton initializations or business operations.
  • hasRegistration<T> accepts registration snapshots and matches exact type, optional key and optional strategy without resolving the dependency.

The matchers do not initialize lazy dependencies or grant access to a container. They use package:matcher, not a global runner adapter. Continue using your normal test or flutter_test runner for assertions and test registration.

Running tests #

Run dart test. The executable example is exercised by the test suite and can also be run directly with dart --packages=.dart_tool/package_config.json example/ark_di_test_example.dart.

Package instructions #

The package includes ark-di-test-scopes for fixture ownership, explicit substitutions, cleanup reporting and metadata matchers. Review instructions before applying them to a project.

dart run skills@ get -p ark_di_test

License #

Apache License 2.0. See LICENSE and NOTICE (included in the package archive).

Project resources #

Russian guide #

Изолированные тестовые scope и matchers для метаданных Ark DI. Приложение использует ark_di, а его тесты могут дополнительно подключать ark_di_test через dev_dependencies. Core не зависит от этого пакета или test runner.

Установка #

dependencies:
  ark_di: ^1.3.0
dev_dependencies:
  ark_di_test: ^1.0.0
  test: ^1.31.2

Требуется Ark DI 1.3.0 или совместимая более новая версия 1.x.

Какую задачу решает #

Тесту нужен отдельный граф объектов, явные подмены и освобождение ресурсов. DiTestScope владеет таким графом. Метод run ожидает очистку перед возвратом результата, в том числе при ошибке тела теста. Общего контейнера и глобального подключения к test runner нет.

Полный тест #

import 'package:ark_di/ark_di.dart';
import 'package:ark_di_test/ark_di_test.dart';
import 'package:test/test.dart';

void main() {
  test('читает отдельную зависимость и закрывает граф', () async {
    final List<int> disposed = <int>[];
    final DiTestScope scope = await DiTestScope.create(
      (final DiBinder binder) =>
          binder.bindInstance<int>(7, dispose: disposed.add),
    );

    await scope.run<void>((final DiResolver resolver) {
      expect(resolver.get<int>(), 7);
      expect(scope.registrations,
          DiTestMatchers.hasRegistration<int>(kind: DiRegistrationKind.instance));
    });

    expect(disposed, <int>[7]);
    expect(scope.diagnostics, DiTestMatchers.hasState(DiContainerState.closed));
  });
}

Если регистрация упала, create ожидает rollback. run предназначен для одного запуска на активном scope; повторный запуск после закрытия и одновременные тела не допускаются. Если подготовка между create и run может упасть, перенесите её в тело либо сразу зарегистрируйте scope.close через addTearDown вашего runner. Само создание scope не устанавливает автоматическую очистку. Не оборачивайте весь widget-тест Flutter в run: дерево widgets может жить дольше его callback. Зарегистрируйте закрытие fixture в test runner и сначала снимите с дерева пользователей её зависимостей.

Подмены и модули #

Собирайте проверяемый граф с явно выбранными fake-реализациями. DiConfiguration принимает типизированный список DiModule; её метод configure можно передать прямо в DiTestScope.create. Исполняемый пример поиска подключает in-memory репозиторий и настоящий сервис поиска отдельными модулями.

DiTestScope.child(parent, configure) владеет только новым child. Родитель остаётся внешним. Действуют обычные правила overrideParent: true, но helper не меняет родительскую фабрику. Чтобы сервис использовал fake из child, зарегистрируйте в child и сам сервис либо создайте отдельный root с проверяемым графом. Подмена в child не переподключает зависимости родительского сервиса.

Ошибки тела и очистки #

Результат Поведение run
Тело и очистка успешны Возвращает результат после закрытия
Ошибка только в теле Передаёт тот же объект ошибки с исходным стеком
Ошибка только в очистке Передаёт ошибку закрытия
Ошибки в обоих этапах Передаёт ошибку тела; отдельно сообщает DiTestCleanupException

Для последнего случая предусмотрен onCleanupError. Без него вторичную ошибку получает Zone, активная при вызове run. Сообщение содержит обе ошибки и оба стека. Ошибка асинхронного reporter также наблюдается и передаётся в эту Zone. Сетевая отправка отчёта не ожидается и не задерживает исходную ошибку теста. Произвольные бизнес-Future не отменяются: helper использует существующий механизм ожидания DI-resolution из core.

Matchers #

  • hasState проверяет DiContainerSnapshot.
  • hasPendingAsyncResolutionCount проверяет локальное число отслеживаемых вызовов, а не количество уникальных инициализаций singleton или бизнес-задач.
  • hasRegistration<T> проверяет snapshots регистраций: точный тип, необязательный ключ и стратегию, не запрашивая саму зависимость.

Matchers не запускают lazy-фабрики и не раскрывают контейнер. Они используют package:matcher, не глобальный адаптер runner. Для регистрации тестов и проверок продолжайте использовать обычный test или flutter_test.

Запуск тестов #

Выполните dart test. Исполняемый пример входит в проверки; отдельно его можно запустить так: dart --packages=.dart_tool/package_config.json example/ark_di_test_example.dart.

Инструкции пакета #

В пакет входит ark-di-test-scopes: владение fixture, явные подмены, сообщения об очистке и matchers метаданных. Перед применением в проекте проверьте содержимое инструкций.

dart run skills@ get -p ark_di_test

Лицензия #

Apache License 2.0. См. LICENSE и NOTICE (включён в архив пакета).

0
likes
155
points
198
downloads

Documentation

Documentation
API reference

Publisher

verified publisherarktelos.dev

Weekly Downloads

Owned test scopes and detached diagnostic matchers for Ark DI.

Homepage
Repository (GitLab)
View/report issues

Topics

#dependency-injection #testing

License

Apache-2.0 (license)

Dependencies

ark_di, matcher

More

Packages that depend on ark_di_test