Communitygithub.com

F# 测试模式

使用 xUnit、FsUnit、Unquote、FsCheck 进行属性基测试、集成测试及测试组织最佳实践。适用于编写 F# 测试时使用 xUnit、FsUnit、Unquote 或 FsCheck。

F# 测试模式 是什么?

此技能提供了一套完整的 F# 测试模式,适用于 xUnit、FsUnit、Unquote 和 FsCheck 等主流 .NET 测试框架。它涵盖了单元测试、异步测试、参数化测试、属性基测试以及依赖模拟,并提供了 ASP.NET Core 集成测试的示例。该技能强调测试组织的最佳实践,例如将单元、集成和属性测试分离到不同目录,并指出了常见的反模式(如测试实现细节、使用可变共享状态)。适合在使用 F# 进行测试开发、审查测试质量、搭建测试基础设施或调试不稳定/慢速测试时激活。该技能还提供了 Dotnet CLI 命令用于运行和筛选测试。

兼容平台~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# 引用的断言库,提供清晰的失败信息
FsCheck.xUnit与 xUnit 集成的属性基测试
NSubstitute模拟 .NET 依赖项
Testcontainers集成测试中的真实基础设施
WebApplicationFactoryASP.NET Core 集成测试

使用 xUnit + FsUnit 的单元测试

基本测试结构

module OrderServiceTests

open Xunit
open FsUnit.Xunit

[<Fact>]
let ``create 将状态设置为 Pending`` () =
    let order = Order.create "cust-1" [ validItem ]
    order.Status |> should equal Pending

[<Fact>]
let ``confirm 将状态改为 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.

相关技能