maybeInitializeOtelForTest function

Future<TestHarness> maybeInitializeOtelForTest({
  1. String serviceName = 'otel-test',
  2. String endpoint = 'http://localhost:4317',
})

Initializes the OpenTelemetry SDK once per test process with in-memory exporters for spans / logs / metrics, and returns the same TestHarness on subsequent calls.

Designed for setUpAll:

late TestHarness harness;
late InMemorySpanExporter spans;

setUpAll(() async {
  harness = await maybeInitializeOtelForTest(
    serviceName: 'my_wrapper-test',
  );
  spans = harness.spans;
});

setUp(() => harness.clear());

Idempotent — calling it from multiple test files in the same process is fine; the SDK is initialized exactly once and every caller gets the same exporters.

  • serviceName becomes service.name on emitted telemetry.
  • endpoint is a dummy — no exporter actually hits the network. Override only if your code-under-test reads it.

Implementation

Future<TestHarness> maybeInitializeOtelForTest({
  String serviceName = 'otel-test',
  String endpoint = 'http://localhost:4317',
}) async {
  if (_shared != null) return _shared!;
  final spanExporter = InMemorySpanExporter();
  final logExporter = InMemoryLogExporter();
  final metricExporter = InMemoryMetricExporter();
  final reader = OnDemandMetricReader(metricExporter);
  await OTel.initialize(
    endpoint: endpoint,
    serviceName: serviceName,
    serviceVersion: '0.0.0-test',
    spanProcessor: SimpleSpanProcessor(spanExporter),
    logRecordProcessor: SimpleLogRecordProcessor(logExporter),
    metricReader: reader,
    detectPlatformResources: false,
  );
  return _shared = TestHarness(
    spans: spanExporter,
    logs: logExporter,
    metrics: metricExporter,
    metricReader: reader,
  );
}