본문으로 건너뛰기
Skillpedia
테스트280k · #184

fsharp-testing

하는 일

이 스킬은 F# 코드의 테스트를 작성하도록 돕습니다. xUnit, FsUnit, Unquote, FsCheck 같은 인기 있는 도구를 사용해 코드가 기대대로 작동하는지 확인하는 방법을 보여 줍니다.

사용하는 경우

  • ✓F# 코드의 새 테스트를 작성할 때.
  • ✓기존 테스트의 품질과 범위를 검토할 때.
  • ✓F# 프로젝트의 테스트 기반을 설정할 때.

스킬 링크

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/fsharp-testing/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/fsharp-testing/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“F#에서 주문이 'Pending' 상태로 생성되는지 확인하는 기본 테스트를 어떻게 작성하나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

이 스킬은 xUnit 같은 테스트 프레임워크와 FsUnit, Unquote 같은 라이브러리를 써서 테스트를 정의합니다. 더 고급 테스트에는 속성 기반 테스트를 위한 FsCheck와 의존성을 대체하기 위한 NSubstitute의 사용법을 보여 줍니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

F# Testing Patterns

Comprehensive testing patterns for F# applications using xUnit, FsUnit, Unquote, FsCheck, and modern .NET testing practices.

When to Activate

  • Writing new tests for F# code
  • Reviewing test quality and coverage
  • Setting up test infrastructure for F# projects
  • Debugging flaky or slow tests

Test Framework Stack

Tool Purpose
xUnit Test framework (standard .NET ecosystem choice)
FsUnit.xUnit F#-friendly assertion syntax for xUnit
Unquote Assertion library using F# quotations for clear failure messages
FsCheck.xUnit Property-based testing integrated with xUnit
NSubstitute Mocking .NET dependencies
Testcontainers Real infrastructure in integration tests
WebApplicationFactory ASP.NET Core integration tests

Unit Tests with xUnit + FsUnit

Basic Test Structure

module OrderServiceTests

open Xunit
open FsUnit.Xunit

[<Fact>]
let ``create sets status to Pending`` () =
    let order = Order.create "cust-1" [ validItem ]
    order.Status |> should equal Pending

[<Fact>]
let ``confirm changes status to Confirmed`` () =
    let order = Order.create "cust-1" [ validItem ]
    let confirmed = Order.confirm order
    confirmed.Status |> should be (ofCase <@ Confirmed @>)

Assertions with Unquote

Unquote uses F# quotations so failure messages show the full expression that failed, not just "expected X got Y".

module OrderValidationTests

open Xunit
open Swensen.Unquote

[<Fact>]
let ``PlaceOrder returns success when request is valid`` () =
    let request = { CustomerId = "cust-123"; Items = [ validItem ] }
    let result = OrderService.placeOrder request
    test <@ Result.isOk result @>

[<Fact>]
let ``order total sums item prices`` () =
    let items = [ { Sku = "A"; Quantity = 2; Price = 10m }
                  { Sku = "B"; Quantity = 1; Price = 5m } ]
    let total = Order.calculateTotal items
    test <@ total = 25m @>

[<Fact>]
let ``validated email rejects empty input`` () =
    let result = ValidatedEmail.create ""
    test <@ Result.isError result @>

Async Tests

[<Fact>]
let ``PlaceOrder returns success when request is valid`` () = task {
    let deps = createTestDeps ()
    let request = { CustomerId = "cust-123"; Items = [ validItem ] }

    let! result = OrderService.placeOrder deps request

    test <@ Result.isOk result @>
}

[<Fact>]
let ``PlaceOrder returns error when items are empty`` () = task {
    let deps = createTestDeps ()
    let request = { CustomerId = "cust-123"; Items = [] }

    let! result = OrderService.placeOrder deps request

    test <@ Result.isError result @>
}

Parameterized Tests with Theory

[<Theory>]
[<InlineData("")>]
[<InlineData("   ")>]
let ``PlaceOrder rejects empty customer 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("user@example.com", true)>]
[<InlineData("user+tag@example.co.uk", true)>]
let ``IsValidEmail returns expected result`` (email: string, expected: bool) =
    test <@ EmailValidator.isValid email = expected @>

Property-Based Testing with FsCheck

Using FsCheck.xUnit

open FsCheck
open FsCheck.Xunit

[<Property>]
let ``order total is always non-negative`` (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 ``serialization roundtrips`` (order: Order) =
    let json = JsonSerializer.Serialize order
    let deserialized = JsonSerializer.Deserialize<Order> json
    deserialized = order

Custom Generators

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 ``valid emails pass validation`` (email: string) =
    EmailValidator.isValid email

Mocking Dependencies

Function Stubs (Preferred)


…
자주 묻는 질문

속성 기반 테스트란 무엇인가요?

특정 입력이 아니라, 자동으로 생성된 넓은 범위의 입력에 대해 코드의 속성이 성립하는지 확인하는 테스트입니다.

'목킹'이란 무엇인가요?

한 부분만 격리해서 테스트하도록 프로그램의 다른 부분을 가짜 버전으로 만드는 것입니다. 예를 들어 주문 로직을 테스트하려고 데이터베이스를 가짜로 만드는 것입니다.

FsUnit 대신 Unquote를 쓰는 이유는 무엇인가요?

테스트가 실패했을 때 어느 부분의 식이 문제를 일으켰는지 정확히 보여 주는, 더 자세한 오류 메시지를 제공하기 때문입니다.

상세 정보

작성자의 원본 설명

F# testing patterns with xUnit, FsUnit, Unquote, FsCheck property-based testing, integration tests, and test organization best practices. Use when writing F# tests with xUnit, FsUnit, Unquote, or FsCheck.

repo: affaan-m/ECC

인기도

GitHub 스타
280k
순위
#184
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬