Communitygithub.com

fsharp-testing

Patrones de prueba en F# con xUnit, FsUnit, Unquote, FsCheck, pruebas basadas en propiedades, pruebas de integración y mejores prácticas de organización.

¿Qué es fsharp-testing?

Este skill proporciona una guía completa para escribir pruebas en F# utilizando el ecosistema moderno de .NET. Cubre desde pruebas unitarias básicas con xUnit y FsUnit hasta pruebas basadas en propiedades con FsCheck, pasando por el uso de Unquote para aserciones con mensajes de error claros. También incluye pautas para crear mocks funcionales y con NSubstitute, así como pruebas de integración para ASP.NET Core usando WebApplicationFactory y Testcontainers. Es útil para desarrolladores que trabajan con F# y desean establecer una infraestructura de pruebas robusta, depurar pruebas lentas o inestables, o mejorar la calidad general del código. El skill enfatiza las prácticas recomendadas y advierte sobre anti-patrones comunes, organizando las pruebas en proyectos separados por tipo (unitarias, integración, propiedades) para mantener la claridad y mantenibilidad.

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

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Patrones de Prueba en F#

Patrones integrales de prueba para aplicaciones F# utilizando xUnit, FsUnit, Unquote, FsCheck y las prácticas modernas de prueba en .NET.

Cuándo Activar

  • Escribir nuevas pruebas para código F#
  • Revisar calidad y cobertura de pruebas
  • Configurar infraestructura de pruebas para proyectos F#
  • Depurar pruebas lentas o inestables

Stack del Marco de Pruebas

HerramientaPropósito
xUnitMarco de pruebas (opción estándar en el ecosistema .NET)
FsUnit.xUnitSintaxis de aserciones amigable para F# en xUnit
UnquoteBiblioteca de aserciones que usa citas de F# para mensajes de error claros
FsCheck.xUnitPruebas basadas en propiedades integradas con xUnit
NSubstituteSimulación de dependencias .NET
TestcontainersInfraestructura real en pruebas de integración
WebApplicationFactoryPruebas de integración de ASP.NET Core

Pruebas Unitarias con xUnit + FsUnit

Estructura Básica de Prueba

module OrderServiceTests

open Xunit
open FsUnit.Xunit

[<Fact>]
let ``create establece el estado a Pendiente`` () =
    let order = Order.create "cust-1" [ validItem ]
    order.Status |> should equal Pending

[<Fact>]
let ``confirm cambia el estado a Confirmado`` () =
    let order = Order.create "cust-1" [ validItem ]
    let confirmed = Order.confirm order
    confirmed.Status |> should be (ofCase <@ Confirmed @>)

Aserciones con Unquote

Unquote usa citas de F# para que los mensajes de error muestren la expresión completa que falló, no solo "se esperaba X pero se obtuvo Y".

module OrderValidationTests

open Xunit
open Swensen.Unquote

[<Fact>]
let ``PlaceOrder devuelve éxito cuando la solicitud es válida`` () =
    let request = { CustomerId = "cust-123"; Items = [ validItem ] }
    let result = OrderService.placeOrder request
    test <@ Result.isOk result @>

[<Fact>]
let ``el total de la orden suma los precios de los artículos`` () =
    let items = [ { Sku = "A"; Quantity = 2; Price = 10m }
                  { Sku = "B"; Quantity = 1; Price = 5m } ]
    let total = Order.calculateTotal items
    test <@ total = 25m @>

[<Fact>]
let ``el correo electrónico validado rechaza entrada vacía`` () =
    let result = ValidatedEmail.create ""
    test <@ Result.isError result @>

Pruebas Asíncronas

[<Fact>]
let ``PlaceOrder devuelve éxito cuando la solicitud es válida`` () = task {
    let deps = createTestDeps ()
    let request = { CustomerId = "cust-123"; Items = [ validItem ] }

    let! result = OrderService.placeOrder deps request

    test <@ Result.isOk result @>
}

[<Fact>]
let ``PlaceOrder devuelve error cuando los artículos están vacíos`` () = task {
    let deps = createTestDeps ()
    let request = { CustomerId = "cust-123"; Items = [] }

    let! result = OrderService.placeOrder deps request

    test <@ Result.isError result @>
}

Pruebas Parametrizadas con Theory

[<Theory>]
[<InlineData("")>]
[<InlineData("   ")>]
let ``PlaceOrder rechaza ID de cliente vacío`` (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 devuelve el resultado esperado`` (email: string, expected: bool) =
    test <@ EmailValidator.isValid email = expected @>

Pruebas Basadas en Propiedades con FsCheck

Usando FsCheck.xUnit

open FsCheck
open FsCheck.Xunit

[<Property>]
let ``el total de la orden siempre es no negativo`` (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 ``la serialización es idempotente`` (order: Order) =
    let json = JsonSerializer.Serialize order
    let deserialized = JsonSerializer.Deserialize<Order> json
    deserialized = order

Generadores Personalizados

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 ``los correos válidos pasan la validación`` (email: string) =
    EmailValidator.isValid email

Simulación de Dependencias

Stubs de Funciones (Preferido)

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 guarda la orden confirmada`` () = 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 para Interfaces .NET

open NSubstitute

[<Fact>]
let ``llama al repositorio con el ID correcto`` () = 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>())
}

Pruebas de Integración 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 devuelve 404 cuando no se encuentra`` () = task {
        let! response = client.GetAsync($"/api/orders/{Guid.NewGuid()}")
        test <@ response.StatusCode = HttpStatusCode.NotFound @>
    }

Organización de Pruebas

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

Anti-patrones Comunes

Anti-patrónSolución
Probar detalles de implementaciónProbar comportamiento y resultados
Estado compartido mutable en pruebasEstado fresco por prueba
Thread.Sleep en pruebas asíncronasUsar Task.Delay con tiempo de espera, o ayudantes de sondeo
Afirmar sobre la salida de sprintfAfirmar sobre valores tipados y coincidencias de patrones
Ignorar CancellationTokenSiempre pasar y verificar cancelación
Omitir pruebas basadas en propiedadesUsar FsCheck para cualquier función con invariantes claros

Skills Relacionados

  • dotnet-patterns - Patrones idiomáticos de .NET, inyección de dependencias y arquitectura
  • csharp-testing - Patrones de prueba en C# (la infraestructura compartida como WebApplicationFactory y Testcontainers también aplica a F#)

Ejecución de Pruebas

# Ejecutar todas las pruebas
dotnet test

# Ejecutar con cobertura
dotnet test --collect:"XPlat Code Coverage"

# Ejecutar proyecto específico
dotnet test tests/MyApp.Tests/

# Filtrar por nombre de prueba
dotnet test --filter "FullyQualifiedName~OrderService"

# Modo de observación durante el desarrollo
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.

Skills relacionados