SuperAPI AI 工具集

dotnet-testing-advanced-aspnet-integration-testing

测试与质量

查看项目

更新于 10-16 06:22

技能介绍

用途:為 ASP.NET Core 專案建立整合測試,驗證多個模組整合後是否正確運作,涵蓋 Routing、Middleware、Request/Response Pipeline、依賴注入與異常處理。

主要能力:以 WebApplicationFactory<Program> 建立記憶體中的 TestServer,搭配 IClassFixture 共享;透過 factory.CreateClient() 取得 HttpClient 發送請求並驗證回應。可繼承 WebApplicationFactory 並覆寫 ConfigureWebHost,移除原本 DbContextOptions 改用 UseInMemoryDatabase,以 services.Replace() 替換外部服務,並用 UseEnvironment("Testing")。提供三層級策略:Level 1 無資料庫與 Service,測 API 輸入輸出、路由與狀態碼;Level 2 以 NSubstitute 建立 Service stub,透過 ConfigureTestServices 注入;Level 3 含真實資料庫操作,以 InMemoryDatabase 替換並呼叫 EnsureCreated()。另涵蓋 GET、POST、PUT、DELETE 的 CRUD 測試重點與測試資料管理。

使用方式:測試類別實作 IClassFixture<WebApplicationFactory<Program>>,建構函式注入 Factory;建立 IntegrationTestBase 封裝 Factory、HttpClient、SeedShipperAsync()、CleanupDatabaseAsync() 並實作 IDisposable。使用 AwesomeAssertions.Web 的 Be200Ok()、Be201Created()、Be400BadRequest()、Be404NotFound() 等斷言,搭配 Satisfy<T>() 驗證強型別回應;以 System.Net.Http.Json 的 PostAsJsonAsync、ReadFromJsonAsync<T>() 簡化 JSON 操作。主專案 Program.cs 需包含 public partial class Program { }。

限制與注意:套件相容性需注意,FluentAssertions < 8.0.0 搭配 FluentAssertions.Web,FluentAssertions >= 8.0.0 搭配 FluentAssertions.Web.v8,AwesomeAssertions >= 8.0.0 搭配 AwesomeAssertions.Web。測試應獨立、避免相依執行順序、避免過度模擬並確實清理資料。其餘細節暫未提供。