Learn

Test a Repository from replay to close

Check replay, update order, operation failures and close with complete executable tests.

v1.0.0Beginnerark_data_layer_test

Русский

Test the values that an Ark Data Layer Repository actually delivers to its subscribers, not only the value left in repository.data.

RepositoryTestObserver<Data> subscribes immediately, records replay and subsequent values, and lets a test await an event count or stream completion. It owns only its subscription. It never closes the Repository or DataSources.

Installation

Keep the observer in development dependencies. The Repository used by your application remains a runtime dependency:

yaml
dependencies:
  ark_data_layer: ^1.2.2

dev_dependencies:
  ark_data_layer_test: ^1.0.0
  test: ^1.31.2

In this package directory, run the current checks and all examples with:

sh
dart pub get
dart test test example

There is no dependency on Flutter, DI, a mock generator or a test runner in the observer library itself. package:test and fake_async are used only to test this package.

When to use it

A test that checks only repository.data can miss an extra publication, lost replay or an incorrect event order. The observer is useful when those notifications are part of your Repository's contract.

For a single method result, a synchronous property or an operation exception, ordinary expect and expectLater remain sufficient. No new assertion framework is required.

First complete test

This is the full lifecycle example, including the concrete Repository and cleanup. Run it with dart test example/lifecycle_test.dart.

dart
import 'package:ark_data_layer/ark_data_layer.dart';
import 'package:ark_data_layer_test/ark_data_layer_test.dart';
import 'package:test/test.dart';

void main() {
  test('records initial data, every commit, and completion', () async {
    final _CounterRepository repository = _CounterRepository();
    final RepositoryTestObserver<int> observer = RepositoryTestObserver<int>(
      repository,
    );
    addTearDown(() async {
      try {
        await observer.cancel();
      } finally {
        await repository.close();
      }
    });

    repository
      ..replace(1)
      ..replace(1);

    await repository.close();
    await observer.waitForDone();

    expect(observer.dataEvents, orderedEquals(<int>[0, 1, 1]));
    expect(observer.streamErrors, isEmpty);
    expect(repository.data, 1);
    expect(repository.commitRevision, 2);
  });
}

final class _CounterRepository extends Repository<int> {
  _CounterRepository()
    : super(
        initialData: 0,
        dataSources: DataSourceContainer(const <DataSource>[]),
      );

  void replace(final int value) => setData(value);
}

What the test proves:

  1. The observer is attached before the operation and receives replay 0.
  2. Both explicit commits are delivered, even though their values are equal.
  3. Closing the test-owned Repository delivers queued events and then done.
  4. Checking the final list after done rejects missing and extra values.
  5. Test cleanup cancels the observation before closing the Repository if an earlier assertion fails. The observer does not take over that ownership.

commitRevision counts commits, so it is two here; replay is not a commit.

Keep a Repository open while awaiting an update

await observer.waitForDataCount(2) waits for at least two recorded values. It includes values already received and returns an unmodifiable snapshot of the event list. More than two events may have arrived by the time it returns.

This is useful for a refresh while the Repository must remain open. It does not prove that no third value will arrive. To assert an exact complete sequence, close a Repository owned by the test, await waitForDone(), then check dataEvents. Cancelling the observation is not an equivalent ending: cancellation can discard undelivered values.

Never close a shared production-scope Repository just to complete this assertion. For a borrowed Repository, test a bounded milestone or use a fresh test-owned instance for a full lifecycle check.

Waiting and failures

Both wait methods default to a five-second deadline and complete as soon as their condition is met. A custom timeout: const Duration(seconds: 1) changes only that wait. No polling or fixed delay is used.

count must be nonnegative and timeout must be positive; invalid arguments throw ArgumentError synchronously. A zero count needs no event, but does not override a previously recorded stream error.

A failed wait completes with RepositoryTestObservationException:

ReasonMeaning
timeoutThe condition was not met before this wait's deadline
completedEarlyThe stream ended before the required event count
cancelledThe observer cancelled before the condition was met
streamErrorThe subscription received an actual stream error

The exception includes the expected count (null means waiting for done), received count, completion/cancellation flags, and the first original stream error when applicable. Its message does not print business data or the error.

Parallel waits have independent deadlines. Finishing a wait removes its timer; timing out does not cancel the subscription, another wait, a refresh or the Repository's cleanup Future.

Three different kinds of failure

  • Operation failure: a method such as refresh() throws or returns a typed result. Assert that method's own contract. It is not automatically a stream error, and no general “Repository error stream” is introduced.
  • Stream failure: an overridden stream delivers an error. The observer records the original error and StackTrace in streamErrors; pending and subsequent waits fail, even if enough data has already been recorded. Recording an error alone is not a test-runner hook: use an awaited observation or explicitly inspect streamErrors so the test asserts its outcome.
  • Cleanup failure: closeRepository() fails. Assert the error from repository.close(), then check that the observed stream still completes. Repeated close() calls keep the same failed Future; cleanup must account for that expected failure rather than accidentally rethrowing it in teardown.

An already-successful wait is not retroactively failed by a later stream error. Continue observing through the boundary relevant to your test.

Ownership and close boundaries

cancel() is idempotent, awaits cancellation of this subscription and preserves any cancellation failure. It does not close the Repository, cancel arbitrary application work, resume somebody else's subscription, or release DataSources.

After cancellation, isCancelled is true and isDone remains false unless natural completion had already happened. Cancel after natural completion is a no-op: isDone stays true and isCancelled stays false. Recorded values remain readable; an already-satisfied event count can still be requested. Unsatisfied waits fail rather than waiting for new events after cancellation.

Repository isClosed becomes true when close starts. During a pending closeRepository(), a new subscription can still receive replay. After await repository.close() has completed, a new subscription receives only done, without replay. The observer does not redefine this runtime contract.

The observer never pauses its subscription. Other paused subscriptions can still delay the Repository's close Future; the observer cannot release them. The deadline on waitForDone() does not bound a separate await repository.close(). See the detailed contract.

Complete examples and reference

Event and error lists are detached and unmodifiable, but business objects are not deep-cloned. The observer retains observed values until it becomes unreachable; it is a test recorder, not a bounded production history store. It does not provide cache policy, persistence, transaction handling or domain error mapping.