engineTest function

  1. @visibleForTesting
  2. @isTest
void engineTest(
  1. String description,
  2. TestCallback callback, {
  3. Engine? engine,
  4. TransportMode transportMode = TransportMode.inMemory,
  5. Map<String, dynamic>? configItems,
  6. EngineConfig? engineConfig,
  7. List<EngineOpt>? options,
  8. bool autoCloseEngine = false,
})

Defines a single test that runs with a dedicated Engine and TestClient.

This helper ensures that the test callback is executed within an AppZone, providing the correct context for routed operations.

  • description: The description of the test.
  • callback: The async function containing the test logic. It receives the Engine and TestClient instances.
  • engine: An optional existing Engine instance to use. If not provided, a new one is created.
  • client: An optional existing TestClient instance to use. If not provided, a new one is created based on transportMode.
  • transportMode: The transport mode for the TestClient (defaults to inMemory).
  • configItems: Initial configuration items for the Engine if a new one is created.
  • engineConfig: An EngineConfig instance for the Engine if a new one is created.
  • options: A list of EngineOpt for the Engine if a new one is created.
  • autoCloseEngine: Close the provided engine after the test finishes. Engines created by this helper are always closed automatically.

Implementation

@visibleForTesting
@isTest
void engineTest(
  String description,
  TestCallback callback, {
  Engine? engine,
  TransportMode transportMode = TransportMode.inMemory,
  Map<String, dynamic>? configItems,
  EngineConfig? engineConfig,
  List<EngineOpt>? options,
  bool autoCloseEngine = false,
}) {
  test_package.test(description, () async {
    final ownsEngine = engine == null;
    final shouldCloseEngine = ownsEngine || autoCloseEngine;

    final testEngine =
        engine ??
        Engine(
          configItems:
              configItems ?? {'app.name': 'Test App', 'app.env': 'testing'},
          config: engineConfig,
          options: options,
        );

    final handler = RoutedRequestHandler(testEngine);
    final client = transportMode == TransportMode.inMemory
        ? TestClient.inMemory(handler)
        : TestClient.ephemeralServer(handler);

    try {
      await AppZone.run(
        engine: testEngine,
        body: () async {
          await callback(testEngine, client);
        },
      );
    } finally {
      await client.close();
      if (shouldCloseEngine) {
        // Ensure providers are booted before cleanup so provider teardown
        // hooks can resolve their dependencies.
        await testEngine.initialize();
        await testEngine.close();
      }
    }
  });
}