Communitygithub.com

fsharp-testing

xUnit、FsUnit、Unquote、FsCheck を使用した F# のテストパターン、プロパティベーステスト、統合テスト、テスト構成のベストプラクティス。F# コードのテスト作成時に利用します。

fsharp-testing とは?

このスキルは、F# アプリケーション向けの包括的なテストパターンを提供します。xUnit をテストフレームワークの基盤とし、FsUnit による F# に適したアサーション構文、Unquote による式全体を表示する明確な失敗メッセージ、FsCheck によるプロパティベーステストを統合します。非同期テスト、パラメータ化テスト(Theory)、モッキング(NSubstitute や関数スタブ)、ASP.NET Core 統合テスト(WebApplicationFactory、Testcontainers)までカバー。テスト構成は Unit、Integration、Properties、Helpers のディレクトリ構造を推奨し、実装の詳細への依存や可変共有状態などのアンチパターンを回避する方法も示します。主に .NET エコシステムの開発者を対象としており、dotnet CLI を用いたテスト実行やカバレッジ収集のコマンドも含まれています。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/fsharp-testing

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

F# テストパターン

xUnit、FsUnit、Unquote、FsCheck、および最新の .NET テスト手法を活用した、F# アプリケーション向けの包括的なテストパターンです。

有効化するタイミング

  • F# コードの新しいテストを作成する場合
  • テストの品質とカバレッジをレビューする場合
  • F# プロジェクトのテストインフラをセットアップする場合
  • 不安定または遅いテストをデバッグする場合

テストフレームワーク構成

ツール目的
xUnitテストフレームワーク(標準的な .NET エコシステムの選択肢)
FsUnit.xUnitxUnit 向け F# フレンドリーなアサーション構文
UnquoteF# クォーテーションを使用した明確な失敗メッセージを提供するアサーションライブラリ
FsCheck.xUnitxUnit と統合されたプロパティベーステスト
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# クォーテーションを使用するため、失敗メッセージには「expected X got 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 ``validateEmail は空の入力を拒否する`` () =
    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 @>
}

.NET インターフェースに対する NSubstitute

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.SleepTask.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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

関連スキル