Created
November 14, 2023 13:58
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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