Specialized skill for ASP.NET Core integration testing. Use when you need to test Web API endpoints, HTTP request/response, middleware, or dependency injection. Covers WebApplicationFactory, TestServer, HttpClient testing, in-memory database configuration, and more. Keywords: integration testing, integration tests, web API testing, WebApplicationFactory, TestServer, HttpClient testing, controller testing, endpoint testing, RESTful API testing, Microsoft.AspNetCore.Mvc.Testing, CreateClient, ConfigureWebHost, AwesomeAssertions.Web, Be200Ok, Be404NotFound, middleware testing, dependency injection testing
| 測試類型 | 測試範圍 | 執行速度 | 維護成本 | 建議比例 | | ---------- | ------------- | -------- | -------- | -------- | | 單元測試 | 單一類別/方法 | 很快 | 低 | 70% | | 整合測試 | 多個元件 | 中等 | 中等 | 20% | | 端對端測試 | 完整流程 | 慢 | 高 | 10% |
透過 WebApplicationFactory<Program> 建立記憶體中的 TestServer,搭配 IClassFixture 在測試類別間共享。
IClassFixture<WebApplicationFactory<Program>>factory.CreateClient() 建立 HttpClient繼承 WebApplicationFactory<Program> 並覆寫 ConfigureWebHost:
DbContextOptions,改用 UseInMemoryDatabaseservices.Replace() 替換外部服務為測試版本builder.UseEnvironment("Testing") 使用測試環境建立 IntegrationTestBase 封裝共用邏輯:
SeedShipperAsync() 等資料準備方法CleanupDatabaseAsync() 清理方法IDisposable 確保資源釋放完整程式碼範例(基本使用、自訂 Factory、測試基底類別)請參考 references/webapplicationfactory-examples.md
提供流暢的 HTTP 狀態碼斷言與強型別回應驗證:
Be200Ok()、Be201Created()、Be400BadRequest()、Be404NotFound() 等response.Should().Be200Ok().And.Satisfy<T>(result => { ... })ReadAsStringAsync() + JsonSerializer.Deserialize<T>() 的冗長程式碼PostAsJsonAsync(url, object) — 取代手動 JsonSerializer.Serialize + new StringContentReadFromJsonAsync<T>() — 取代手動 ReadAsStringAsync + JsonSerializer.Deserialize完整斷言與 JSON 操作範例請參考 references/assertion-and-json-examples.md
| Level | 特色 | 測試重點 | Factory 設定 | | ----- | ------------------------ | -------------------------------- | ------------------------- | | 1 | 無資料庫、無 Service | API 輸入輸出、路由、狀態碼 | 直接使用原始 Factory | | 2 | 有 Service(NSubstitute)| 依賴注入配置、服務互動 | ConfigureTestServices | | 3 | 完整架構 + 資料庫 | 真實 CRUD、資料完整性 | InMemoryDatabase 替換 |
最簡單的形式,直接使用 WebApplicationFactory<Program> 測試各個 API 端點的輸入輸出。
使用 NSubstitute 建立 Service stub,透過自訂 Factory 的 ConfigureTestServices 注入測試用服務。
包含真實的資料庫操作,移除原本的 DbContextOptions 並改用 InMemoryDatabase,在測試中呼叫 EnsureCreated() 建立結構。
完整三個層級的程式碼範例請參考 references/three-level-testing-strategy.md
| 操作 | 測試重點 | | ------ | ---------------------------------------------- | | GET | 單一資源查詢、集合查詢、不存在資源回傳 404 | | POST | 建立成功回傳 201、驗證錯誤回傳 400 | | PUT | 更新成功、不存在資源處理 | | DELETE | 刪除成功回傳 204、不存在資源回傳 404 |
CleanupDatabaseAsync() 確保乾淨狀態SeedShipperAsync() 等方法準備測試資料Satisfy<T>() 驗證回應內容的正確性完整的 CRUD 操作測試程式碼請參考 references/crud-test-examples.md
tests/
├── Sample.WebApplication.UnitTests/ # 單元測試
├── Sample.WebApplication.Integration.Tests/ # 整合測試
│ ├── Controllers/ # 控制器整合測試
│ ├── Infrastructure/ # 測試基礎設施
│ │ └── CustomWebApplicationFactory.cs
│ ├── IntegrationTestBase.cs # 測試基底類別
│ └── GlobalUsings.cs
└── Sample.WebApplication.E2ETests/ # 端對端測試
'ObjectAssertions' 未包含 'Be200Ok' 的定義此錯誤通常是因為安裝了不相容的斷言套件組合。請確認基礎斷言庫與 Web 擴充套件版本一致。
Program 類別無法存取確保主專案的 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 |
<!-- 推薦組合 -->
<PackageReference Include="AwesomeAssertions" Version="9.4.0" />
<PackageReference Include="AwesomeAssertions.Web" Version="1.9.6" />
CustomWebApplicationFactory.cs,配置測試用 DI 容器與資料庫替換IntegrationTestBase.cs 測試基底類別,包含資料準備與清理方法*ControllerTests.cs),涵蓋 CRUD 操作驗證.csproj,加入 Microsoft.AspNetCore.Mvc.Testing 與 AwesomeAssertions.WebProgram.cs 包含 public partial class Program { } 以支援測試存取unit-test-fundamentals - 單元測試基礎nsubstitute-mocking - 使用 NSubstitute 進行模擬awesome-assertions-guide - AwesomeAssertions 流暢斷言testcontainers-database - 使用 Testcontainers 進行容器化資料庫測試npx skills add kevintsengtw/dotnet 测试 — 高级 ASP.NET 集成测试下载完整 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