Recipes

Test overlapping executions

Use two virtual clocks and explicit gates to check Source identity, completion and all three elapsed intervals.

v1.2.0Intermediateusecase_forge_test

Suppose two catalog screens submit work at the same time. Both UseCases assign ID 1. Waiting for “any finished event with ID 1” can accidentally assert the other screen's result. This test waits for Source plus ID, then checks the time spent before and after processing starts.

Install and run

Add these dependencies to a Dart package:

yaml
dependencies:
  usecase_forge: ^1.5.0
dev_dependencies:
  test: ^1.26.3
  usecase_forge_test: ^1.2.0

Save the complete code below as test/observing_executions_test.dart, resolve dependencies with dart pub get, then run:

shell
dart test test/observing_executions_test.dart

What the test controls

Each UseCase has two Completers. The start gate holds onProcessingRegistryAdd; its time belongs to beforeProcessing. The handler gate holds the actual handler after processingStarted. There are no guessed sleeps.

  1. Submit one Command to each UseCase and retain their distinct Sources.
  2. Advance A by 110 ms and B by 20 ms, then release both start gates.
  3. Wait for processingStarted from each Source before advancing again.
  4. Advance A by 90 ms and B by 50 ms, release the handlers and wait for each terminal event.
  5. Assert A = 110 + 90 = 200 ms and B = 20 + 50 = 70 ms.
  6. Close A and create a replacement: its first ID is again 1, but its Source is new.

The one-second timeout is a real-time failure guard for each wait, not virtual work duration. Virtual time moves only through advance.

Complete test

dart
import 'dart:async';

import 'package:test/test.dart';
import 'package:usecase_forge/usecase_forge.dart';
import 'package:usecase_forge_test/usecase_forge_test.dart';

void main() {
  test(
    'two CatalogUseCases keep separate IDs and measured intervals',
    () async {
      final UseCaseExecutionTestObserver observer =
          UseCaseExecutionTestObserver();
      final TestUseCaseClock clockA = TestUseCaseClock();
      final TestUseCaseClock clockB = TestUseCaseClock();
      final _CatalogUseCase a = _CatalogUseCase(clockA, observer);
      final _CatalogUseCase b = _CatalogUseCase(clockB, observer);
      addTearDown(() async {
        await a.close();
        await b.close();
        observer.dispose();
      });

      a.add(const _SearchCatalog());
      b.add(const _SearchCatalog());
      // submitted is synchronous; each source has its own local execution 1.
      final UseCaseExecutionSource sourceA = observer.events[0].source!;
      final UseCaseExecutionSource sourceB = observer.events
          .firstWhere(
            (final UseCaseExecutionEvent event) =>
                !identical(event.source, sourceA),
          )
          .source!;

      clockA.advance(const Duration(milliseconds: 110));
      clockB.advance(const Duration(milliseconds: 20));
      a.startGate.complete();
      b.startGate.complete();
      await observer.waitForEvent(
        (final UseCaseExecutionEvent event) =>
            identical(event.source, sourceA) &&
            event.kind == UseCaseExecutionEventKind.processingStarted,
        timeout: const Duration(seconds: 1),
      );
      await observer.waitForEvent(
        (final UseCaseExecutionEvent event) =>
            identical(event.source, sourceB) &&
            event.kind == UseCaseExecutionEventKind.processingStarted,
        timeout: const Duration(seconds: 1),
      );

      clockA.advance(const Duration(milliseconds: 90));
      clockB.advance(const Duration(milliseconds: 50));
      a.handlerGate.complete();
      b.handlerGate.complete();
      final UseCaseExecutionEvent resultA = await observer.waitForTerminal(
        sourceA,
        const UseCaseExecutionId(1),
        timeout: const Duration(seconds: 1),
      );
      final UseCaseExecutionEvent resultB = await observer.waitForTerminal(
        sourceB,
        const UseCaseExecutionId(1),
        timeout: const Duration(seconds: 1),
      );
      expect(resultA.result, UseCaseExecutionResult.completed);
      expect(resultB.result, UseCaseExecutionResult.completed);
      expect(
        resultA.timing!.beforeProcessing,
        const Duration(milliseconds: 110),
      );
      expect(resultA.timing!.processing, const Duration(milliseconds: 90));
      expect(resultA.timing!.total, const Duration(milliseconds: 200));
      expect(
        resultB.timing!.beforeProcessing,
        const Duration(milliseconds: 20),
      );
      expect(resultB.timing!.processing, const Duration(milliseconds: 50));
      expect(resultB.timing!.total, const Duration(milliseconds: 70));
      expect(identical(sourceA, sourceB), isFalse);

      await a.close();
      final _CatalogUseCase replacement = _CatalogUseCase(
        TestUseCaseClock(),
        observer,
      );
      replacement.add(const _SearchCatalog());
      expect(identical(observer.events.last.source, sourceA), isFalse);
      expect(observer.events.last.id, const UseCaseExecutionId(1));
      await replacement.close();
    },
  );
}

final class _SearchCatalog extends UseCaseCommand {
  const _SearchCatalog();
}

final class _CatalogUseCase extends UseCase<int> {
  _CatalogUseCase(
    final TestUseCaseClock clock,
    final UseCaseExecutionTestObserver observer,
  ) : super(initialState: 0, clock: clock, executionObserver: observer) {
    registerCommand<_SearchCatalog>((
      final _SearchCatalog command,
      final UseCaseExecutionContext<int> context,
    ) async {
      await handlerGate.future;
      context.publish(1);
    });
  }

  final Completer<void> startGate = Completer<void>();
  final Completer<void> handlerGate = Completer<void>();

  @override
  Future<void> onProcessingRegistryAdd(
    final UseCaseExecutionEntry<UseCaseCommand> entry,
  ) => startGate.future;
}

Collector lifetime and limits

UseCaseExecutionTestObserver is separate from the Snapshot-oriented UseCaseTestObserver<S>. It retains an immutable chronological event window: 500 events and 64 pending waits by default. Configure positive limits when necessary and check evictedEventCount before treating the window as complete.

waitForTerminal accepts either finished or rejected. It first checks retained events and then waits; it does not assume every submission enters processing. In this example we separately require completed, so rejection cannot masquerade as successful work.

A timeout removes that wait. clear() fails earlier waits as reset; dispose() fails waits and releases retained records. Neither closes a UseCase nor removes its constructor callback. Close the owned UseCases as teardown does here.

The published executable source is the same test. For custom clocks and partial measurements, read Observe individual executions; to inspect a running VM application, open All executions.