Complete guide to ASP.NET Core WebApi integration testing. Use this when you need to run integration tests against WebApi endpoints or validate ProblemDetails error formats. Covers WebApplicationFactory, IExceptionHandler, multi-container orchestration with Testcontainers, Flurl URL construction, and HTTP assertions with AwesomeAssertions. Keywords: webapi integration testing, WebApplicationFactory, asp.net core integration test, webapi integration testing, IExceptionHandler, ProblemDetails, ValidationProblemDetails, AwesomeAssertions, Flurl, Respawn, Be201Created, Be400BadRequest, multi-container testing, Collection Fixture, global exception handling
完成本技能學習後,您將能夠:
IExceptionHandler 實作現代化異常處理ProblemDetails 和 ValidationProblemDetails 標準格式ASP.NET Core 8+ 引入的 IExceptionHandler 介面提供了比傳統 middleware 更優雅的錯誤處理方式。GlobalExceptionHandler 依據例外類型(KeyNotFoundException → 404、ArgumentException → 400、其他 → 500)產生對應的 ProblemDetails 回應。
RFC 7807 定義的統一錯誤回應格式:
| 欄位 | 說明 |
| ---------- | ------------------ |
| type | 問題類型的 URI |
| title | 簡短的錯誤描述 |
| status | HTTP 狀態碼 |
| detail | 詳細的錯誤說明 |
| instance | 發生問題的實例 URI |
繼承自 ProblemDetails,額外包含 errors 字典,記錄每個欄位的驗證錯誤訊息。
FluentValidation 異常處理器實作 IExceptionHandler 介面,專門處理 ValidationException,將驗證錯誤轉換為標準的 ValidationProblemDetails 格式回應。處理器之間按照註冊順序執行,特定處理器(如 FluentValidation)必須在全域處理器之前註冊。
完整實作程式碼請參閱 references/exception-handler-details.md
測試基礎設施由三個核心組件構成:
WebApplicationFactory<Program>,配置多容器(PostgreSQL + Redis)與 DI 替換(如 FakeTimeProvider)完整基礎設施程式碼請參閱 references/test-infrastructure.md
// 傳統方式
var url = $"/products?pageSize={pageSize}&page={page}&keyword={keyword}";
// 使用 Flurl
var url = "/products"
.SetQueryParam("pageSize", 5)
.SetQueryParam("page", 2)
.SetQueryParam("keyword", "特殊");
涵蓋成功建立產品(201 Created)、驗證錯誤(400 BadRequest + ValidationProblemDetails)、資源不存在(404 NotFound + ProblemDetails)、分頁查詢(200 OK + PagedResult)等完整測試範例,以及 TestHelpers 資料管理策略。
完整測試範例與資料管理程式碼請參閱 references/test-examples.md
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="AwesomeAssertions" Version="9.4.0" />
<PackageReference Include="Testcontainers.PostgreSql" Version="4.11.0" />
<PackageReference Include="Testcontainers.Redis" Version="4.11.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.0" />
<PackageReference Include="Flurl" Version="4.0.0" />
<PackageReference Include="Respawn" Version="7.0.0" />
src/
├── Api/ # WebApi 層
├── Application/ # 應用服務層
├── Domain/ # 領域模型
└── Infrastructure/ # 基礎設施層
tests/
└── Integration/
├── Fixtures/
│ ├── TestWebApplicationFactory.cs
│ ├── IntegrationTestCollection.cs
│ └── IntegrationTestBase.cs
├── Handlers/
│ ├── GlobalExceptionHandler.cs
│ └── FluentValidationExceptionHandler.cs
├── Helpers/
│ ├── DatabaseManager.cs
│ └── TestHelpers.cs
├── SqlScripts/
│ └── Tables/
└── Controllers/
└── ProductsControllerTests.cs
TestWebApplicationFactory.cs,配置多容器(PostgreSQL + Redis)與 DI 替換IntegrationTestCollection.cs 與 IntegrationTestBase.cs 測試基礎設施DatabaseManager.cs,整合 Respawn 進行測試資料清理GlobalExceptionHandler.cs 與 FluentValidationExceptionHandler.cs 異常處理器本技能內容提煉自「老派軟體工程師的測試修練 - 30 天挑戰」系列文章:
dotnet-testing-advanced-aspnet-integration-testing - ASP.NET Core 基礎整合測試dotnet-testing-advanced-testcontainers-database - 資料庫容器測試dotnet-testing-advanced-testcontainers-nosql - NoSQL 容器測試dotnet-testing-fluentvalidation-testing - FluentValidation 測試npx skills add kevintsengtw/dotnet-testing-advanced-webapi-integration-testing下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer