Skip to content

Instantly share code, notes, and snippets.

@stand-sure
Created November 14, 2023 13:58
Show Gist options
  • Save stand-sure/7a65996297956486f3ea633ad836353f to your computer and use it in GitHub Desktop.
Save stand-sure/7a65996297956486f3ea633ad836353f to your computer and use it in GitHub Desktop.
How to Verify that an OpenTelemetry Trace is produced in a unit test
[Fact]
public async Task InterceptShouldTrace()
{
IList<Activity> exportedActivities = new List<Activity>();
IHostBuilder hostBuilder = Host.CreateDefaultBuilder();
var source = Guid.NewGuid().ToString("N");
hostBuilder.ConfigureServices((_, serviceCollection) =>
{
serviceCollection.AddOpenTelemetry()
.WithTracing(builder =>
{
builder.AddSource(source);
builder.AddInMemoryExporter(exportedActivities);
});
serviceCollection.AddSingleton(TracerProvider.Default.GetTracer(source));
});
IHost host = hostBuilder.Build();
await host.StartAsync();
var tracer = ActivatorUtilities.GetServiceOrCreateInstance<Tracer>(host.Services);
var tracingInterceptor = new TracingInterceptor(tracer);
var interceptInvocation = Mock.Of<IInvocation>(invocation =>
invocation.TargetType == typeof(MyTraceTarget) &&
invocation.Method == typeof(MyTraceTarget).GetMethod(nameof(MyTraceTarget.GetSomething)));
tracingInterceptor.Intercept(interceptInvocation);
exportedActivities.Should().Contain(activity => activity.OperationName == $"{nameof(MyTraceTarget)}.{nameof(MyTraceTarget.GetSomething)}" && activity.TagObjects.Any(pair => pair.Key == "injected"));
await host.StopAsync();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment