Communitygithub.com

fsharp-testing

F# 測試模式,涵蓋 xUnit、FsUnit、Unquote、FsCheck 屬性測試、整合測試與測試組織最佳實務。適用於以 xUnit、FsUnit、Unquote 或 FsCheck 撰寫 F# 測試。

fsharp-testing 是什麼?

此技能提供一套完整的 F# 應用程式測試模式,深度整合 xUnit、FsUnit、Unquote、FsCheck 以及現代 .NET 測試實務。它適用於任何需要為 F# 程式碼撰寫新測試、檢視測試品質與涵蓋率、設定測試基礎設施,或偵錯不穩定或緩慢測試的情境。該技能詳細涵蓋了從單元測試(使用 FsUnit 和 Unquote 進行斷言)、非同步測試、參數化測試,到 FsCheck 屬性測試與自訂生成器的進階用法。此外,它也說明了如何透過函式樁(Function Stubs)或 NSubstitute 來模擬相依性,並提供了 ASP.NET Core 整合測試(使用 WebApplicationFactory)的實作方式。技能支援的開發平台包括所有支援 .NET 的編輯器與 IDE(例如 Visual Studio、JetBrains Rider、VS Code),並透過 CLI 指令整合至 CI/CD 流程。它以清楚的對照表指出常見反模式及其修正方法,並推薦了相關技能(如 dotnet-patterns 與 csharp-testing)作為補充。最終,它讓開發者能基於一致的模式建立可靠、可維護且具高涵蓋率的測試套件。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/fsharp-testing

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

F# 測試模式

適用於 F# 應用程式的完整測試模式,使用 xUnit、FsUnit、Unquote、FsCheck 與現代 .NET 測試實務。

何時啟用

  • 為 F# 程式碼撰寫新的測試
  • 審查測試品質與涵蓋率
  • 為 F# 專案設定測試基礎設施
  • 偵錯不穩定或緩慢的測試

測試框架堆疊

工具用途
xUnit測試框架(標準 .NET 生態系統選擇)
FsUnit.xUnit為 xUnit 提供 F# 友善的斷言語法
Unquote使用 F# 引號(quotations)的斷言函式庫,提供清晰的失敗訊息
FsCheck.xUnit與 xUnit 整合的屬性測試
NSubstitute模擬 .NET 相依性
Testcontainers在整合測試中使用真實基礎設施
WebApplicationFactoryASP.NET Core 整合測試

使用 xUnit + FsUnit 的單元測試

基本測試結構

module OrderServiceTests

open Xunit
open FsUnit.Xunit

[<Fact>]
let ``建立後狀態設為 Pending`` () =
    let order = Order.create "cust-1" [ validItem ]
    order.Status |> should equal Pending

[<Fact>]
let ``確認後狀態變更為 Confirmed`` () =
    let order = Order.create "cust-1" [ validItem ]
    let confirmed = Order.confirm order
    confirmed.Status |> should be (ofCase <@ Confirmed @>)

使用 Unquote 的斷言

Unquote 使用 F# 引號,因此失敗訊息會顯示失敗的完整運算式,而不僅僅是「預期 X 得到 Y」。

module OrderValidationTests

open Xunit
open Swensen.Unquote

[<Fact>]
let ``PlaceOrder 在請求有效時回傳成功`` () =
    let request = { CustomerId = "cust-123"; Items = [ validItem ] }
    let result = OrderService.placeOrder request
    test <@ Result.isOk result @>

[<Fact>]
let ``訂單總金額為各項目價格總和`` () =
    let items = [ { Sku = "A"; Quantity = 2; Price = 10m }
                  { Sku = "B"; Quantity = 1; Price = 5m } ]
    let total = Order.calculateTotal items
    test <@ total = 25m @>

[<Fact>]
let ``驗證電子郵件拒絕空白輸入`` () =
    let result = ValidatedEmail.create ""
    test <@ Result.isError result @>

非同步測試

[<Fact>]
let ``PlaceOrder 在請求有效時回傳成功`` () = task {
    let deps = createTestDeps ()
    let request = { CustomerId = "cust-123"; Items = [ validItem ] }

    let! result = OrderService.placeOrder deps request

    test <@ Result.isOk result @>
}

[<Fact>]
let ``PlaceOrder 在項目清單為空時回傳錯誤`` () = task {
    let deps = createTestDeps ()
    let request = { CustomerId = "cust-123"; Items = [] }

    let! result = OrderService.placeOrder deps request

    test <@ Result.isError result @>
}

使用 Theory 的參數化測試

[<Theory>]
[<InlineData("")>]
[<InlineData("   ")>]
let ``PlaceOrder 拒絕空的客戶 ID`` (customerId: string) =
    let request = { CustomerId = customerId; Items = [ validItem ] }
    let result = OrderService.placeOrder request
    result |> should be (ofCase <@ Error @>)

[<Theory>]
[<InlineData("", false)>]
[<InlineData("a", false)>]
[<InlineData("[email protected]", true)>]
[<InlineData("[email protected]", true)>]
let ``IsValidEmail 回傳預期結果`` (email: string, expected: bool) =
    test <@ EmailValidator.isValid email = expected @>

使用 FsCheck 的屬性測試

使用 FsCheck.xUnit

open FsCheck
open FsCheck.Xunit

[<Property>]
let ``訂單總金額永遠非負`` (items: NonEmptyList<PositiveInt * decimal>) =
    let orderItems =
        items.Get
        |> List.map (fun (qty, price) ->
            { Sku = "SKU"; Quantity = qty.Get; Price = abs price })
    let total = Order.calculateTotal orderItems
    total >= 0m

[<Property>]
let ``序列化往返`` (order: Order) =
    let json = JsonSerializer.Serialize order
    let deserialized = JsonSerializer.Deserialize<Order> json
    deserialized = order

自訂生成器

type OrderGenerators =
    static member ValidEmail () =
        gen {
            let! user = Gen.elements [ "alice"; "bob"; "carol" ]
            let! domain = Gen.elements [ "example.com"; "test.org" ]
            return $"{user}@{domain}"
        }
        |> Arb.fromGen

[<Property(Arbitrary = [| typeof<OrderGenerators> |])>]
let ``有效的電子郵件通過驗證`` (email: string) =
    EmailValidator.isValid email

模擬相依性

函式樁(偏好做法)

let createTestDeps () =
    let mutable savedOrders = []
    { FindOrder = fun id -> task { return Map.tryFind id testData }
      SaveOrder = fun order -> task { savedOrders <- order :: savedOrders }
      SendNotification = fun _ -> Task.CompletedTask }

[<Fact>]
let ``PlaceOrder 儲存已確認的訂單`` () = task {
    let mutable saved = []
    let deps =
        { createTestDeps () with
            SaveOrder = fun order -> task { saved <- order :: saved } }

    let! _ = OrderService.placeOrder deps validRequest

    test <@ saved.Length = 1 @>
}

使用 NSubstitute 模擬 .NET 介面

open NSubstitute

[<Fact>]
let ``使用正確的 ID 呼叫儲存庫`` () = task {
    let repo = Substitute.For<IOrderRepository>()
    repo.FindByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
        .Returns(Task.FromResult(Some testOrder))

    let service = OrderService(repo)
    let! _ = service.GetOrder(testOrder.Id, CancellationToken.None)

    do! repo.Received(1).FindByIdAsync(testOrder.Id, Arg.Any<CancellationToken>())
}

ASP.NET Core 整合測試

type OrderApiTests (factory: WebApplicationFactory<Program>) =
    interface IClassFixture<WebApplicationFactory<Program>>

    let client =
        factory.WithWebHostBuilder(fun builder ->
            builder.ConfigureServices(fun services ->
                services.RemoveAll<DbContextOptions<AppDbContext>>() |> ignore
                services.AddDbContext<AppDbContext>(fun options ->
                    options.UseInMemoryDatabase("TestDb") |> ignore) |> ignore))
            .CreateClient()

    [<Fact>]
    member _.``GET order 在找不到時回傳 404`` () = task {
        let! response = client.GetAsync($"/api/orders/{Guid.NewGuid()}")
        test <@ response.StatusCode = HttpStatusCode.NotFound @>
    }

測試組織

tests/
  MyApp.Tests/
    Unit/
      OrderServiceTests.fs
      PaymentServiceTests.fs
    Integration/
      OrderApiTests.fs
      OrderRepositoryTests.fs
    Properties/
      OrderPropertyTests.fs
    Helpers/
      TestData.fs
      TestDeps.fs

常見反模式

反模式修正建議
測試實作細節測試行為與結果
可變的共享測試狀態每個測試使用全新狀態
在非同步測試中使用 Thread.Sleep使用 Task.Delay 搭配逾時,或輪詢輔助程式
對 sprintf 輸出進行斷言對型別值與模式比對進行斷言
忽略 CancellationToken始終傳遞並驗證取消
跳過屬性測試對任何具有明確不變量的函式使用 FsCheck

相關技能

  • dotnet-patterns - 慣用的 .NET 模式、相依性注入與架構
  • csharp-testing - C# 測試模式(WebApplicationFactory 和 Testcontainers 等共享基礎設施也適用於 F#)

執行測試

# 執行所有測試
dotnet test

# 執行測試並收集涵蓋率
dotnet test --collect:"XPlat Code Coverage"

# 執行特定專案的測試
dotnet test tests/MyApp.Tests/

# 依測試名稱篩選
dotnet test --filter "FullyQualifiedName~OrderService"

# 開發期間監看模式
dotnet watch test --project tests/MyApp.Tests/

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

相關技能