engineTest function
- @visibleForTesting
- @isTest
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 theEngineandTestClientinstances.engine: An optional existingEngineinstance to use. If not provided, a new one is created.client: An optional existingTestClientinstance to use. If not provided, a new one is created based ontransportMode.transportMode: The transport mode for theTestClient(defaults toinMemory).configItems: Initial configuration items for theEngineif a new one is created.engineConfig: AnEngineConfiginstance for theEngineif a new one is created.options: A list ofEngineOptfor theEngineif 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();
}
}
});
}