Skip to content

Commit f075128

Browse files
authored
Solve 404 error in unit test (#5145)
1 parent f5c1160 commit f075128

File tree

3 files changed

+36
-8
lines changed

3 files changed

+36
-8
lines changed

test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -947,6 +947,7 @@ public async Task DiagnosticSourceExceptionCallBackIsNotReceivedForExceptionsHan
947947
int numberOfUnSubscribedEvents = 0;
948948
int numberOfSubscribedEvents = 0;
949949
int numberOfExceptionCallbacks = 0;
950+
bool exceptionHandled = false;
950951

951952
// configure SDK
952953
this.tracerProvider = Sdk.CreateTracerProviderBuilder()
@@ -991,18 +992,18 @@ public async Task DiagnosticSourceExceptionCallBackIsNotReceivedForExceptionsHan
991992
})
992993
.Build();
993994

995+
TestMiddleware.Create(builder => builder
996+
.UseExceptionHandler(handler =>
997+
handler.Run(async (ctx) =>
998+
{
999+
exceptionHandled = true;
1000+
await ctx.Response.WriteAsync("handled");
1001+
})));
1002+
9941003
using (var client = this.factory
9951004
.WithWebHostBuilder(builder =>
9961005
{
9971006
builder.ConfigureLogging(loggingBuilder => loggingBuilder.ClearProviders());
998-
builder.Configure(app => app
999-
.UseExceptionHandler(handler =>
1000-
{
1001-
handler.Run(async (ctx) =>
1002-
{
1003-
await ctx.Response.WriteAsync("handled");
1004-
});
1005-
}));
10061007
})
10071008
.CreateClient())
10081009
{
@@ -1020,6 +1021,7 @@ public async Task DiagnosticSourceExceptionCallBackIsNotReceivedForExceptionsHan
10201021
Assert.Equal(0, numberOfExceptionCallbacks);
10211022
Assert.Equal(0, numberOfUnSubscribedEvents);
10221023
Assert.Equal(2, numberOfSubscribedEvents);
1024+
Assert.True(exceptionHandled);
10231025
}
10241026

10251027
public void Dispose()

test/TestApp.AspNetCore/Program.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ public static void Main(string[] args)
4747

4848
app.UseMiddleware<ActivityMiddleware>();
4949

50+
app.AddTestMiddleware();
51+
5052
app.Run();
5153
}
5254
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Copyright The OpenTelemetry Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
namespace TestApp.AspNetCore;
5+
6+
public static class TestMiddleware
7+
{
8+
private static readonly AsyncLocal<Action<IApplicationBuilder>?> Current = new();
9+
10+
public static IApplicationBuilder AddTestMiddleware(this IApplicationBuilder builder)
11+
{
12+
if (Current.Value is { } configure)
13+
{
14+
configure(builder);
15+
}
16+
17+
return builder;
18+
}
19+
20+
public static void Create(Action<IApplicationBuilder> action)
21+
{
22+
Current.Value = action;
23+
}
24+
}

0 commit comments

Comments
 (0)