Custom Middleware Testing: xUnit ile ASP.NET Core Pipeline Testi
Middleware, HTTP isteğini işleyen ve yanıtı döndüren bileşendir. Örneğin authentication, logging, error handling gibi işlemler middleware'de yapılır. Doğru çalışıp çalışmadığını test etmek çok önemlidir çünkü yanlış middleware tüm uygulamayı etkileyebilir.
Önce xUnit ve Moq paketlerini yükleyin:
1dotnet add package xunit2dotnet add package xunit.runner.visualstudio3dotnet add package MoqBasit bir logging middleware oluşturalım:
1public class LoggingMiddleware2{3private readonly RequestDelegate _next;45public LoggingMiddleware(RequestDelegate next)6{7_next = next;8}910public async Task InvokeAsync(HttpContext context)11{12context.Response.Headers.Add("X-Custom-Header", "TestValue");13await _next(context);14}15}xUnit ile test sınıfı oluşturun:
Reklam · TEST
AdSense Test ReklamıYazı arası (gönderi içi) · Yazı arası
1public class LoggingMiddlewareTests2{3[Fact]4public async Task Middleware_ShouldAddCustomHeader()5{6// Arrange7var context = new DefaultHttpContext();8var middleware = new LoggingMiddleware(async (ctx) => 9{10await ctx.Response.WriteAsync("OK");11});1213// Act14await middleware.InvokeAsync(context);1516// Assert17Assert.True(context.Response.Headers.ContainsKey("X-Custom-Header"));18Assert.Equal("TestValue", context.Response.Headers["X-Custom-Header"].ToString());19}20}Tüm pipeline'ı test etmek için WebApplicationFactory kullanın:
1public class PipelineTests: IClassFixture<WebApplicationFactory<Program>>2{3private readonly WebApplicationFactory<Program> _factory;45public PipelineTests(WebApplicationFactory<Program> factory)6{7_factory = factory;8}910[Fact]11public async Task Pipeline_ShouldReturnCustomHeader()12{13var client = _factory.CreateClient();14var response = await client.GetAsync("/");1516Assert.True(response.Headers.Contains("X-Custom-Header"));17}18}1dotnet testBeklenen çıktı:
1Test Run Successful.2Total tests: 23Passed: 24Failed: 0Middleware test etmek üç adımda yapılır: DefaultHttpContext oluştur, middleware'i çağır, sonucu kontrol et. WebApplicationFactory ile gerçek pipeline'da test edebilirsiniz.
0 yorum