CommunityProgramación y desarrollogithub.com

github/csharp-xunit

Obtén las mejores prácticas para pruebas unitarias con XUnit, incluyendo pruebas basadas en datos.

¿Qué es csharp-xunit?

Este skill proporciona orientación experta y recomendaciones sobre pruebas unitarias en C# utilizando el framework XUnit. Está diseñado para ayudar a desarrolladores y agentes de IA a aplicar patrones de prueba robustos, incluyendo el uso de pruebas parametrizadas (data-driven tests) con atributos como [Theory] y [InlineData], [MemberData], o [ClassData]. El skill promueve prácticas estándar de la industria, como la organización de pruebas siguiendo el patrón AAA (Arrange, Act, Assert), el uso de fixtures compartidos para reducir la duplicación de código, y la integración con herramientas de cobertura de código. Es compatible con entornos .NET (incluyendo .NET Core y .NET 5/6/7/8) y se integra naturalmente con sistemas CI/CD. Al basarse en la documentación oficial y las convenciones de la comunidad, este skill asegura que las suites de pruebas sean mantenibles, legibles y efectivas para detectar regresiones.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/github/awesome-copilot/tree/main/skills/csharp-xunit

Installed? Explore more Programación y desarrollo skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Preguntar en tu IA favorita

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

Documentación

¿Qué hace csharp-xunit?

Obtén las mejores prácticas para pruebas unitarias con XUnit, incluyendo pruebas basadas en datos.

Visión General

Este skill te guía en la implementación de pruebas unitarias en C# con XUnit, cubriendo desde la configuración básica hasta patrones avanzados como pruebas basadas en datos, uso de mocks y buenas prácticas de organización.

Prerrequisitos

  • Conocimiento básico de C# y .NET
  • Proyecto con soporte para XUnit (paquete NuGet xunit)
  • (Opcional) Paquete xunit.runner.visualstudio para integración con el IDE

Instalación

  1. Agrega el paquete XUnit a tu proyecto:

    dotnet add package xunit
    
  2. (Opcional) Para el ejecutor de pruebas desde la línea de comandos:

    dotnet add package xunit.runner.visualstudio
    

Estructura de Prueba Recomendada

Sigue el patrón AAA (Arrange, Act, Assert) para cada prueba:

  • Arrange: Configura las condiciones iniciales (objetos, datos de entrada, mocks).
  • Act: Ejecuta la acción a probar (llamada al método).
  • Assert: Verifica que el resultado sea el esperado.

Ejemplo Básico

using Xunit;

public class CalculadoraTests
{
    [Fact]
    public void Sumar_DosNumeros_DevuelveSuma()
    {
        // Arrange
        var calc = new Calculadora();
        int a = 2, b = 3;

        // Act
        var resultado = calc.Sumar(a, b);

        // Assert
        Assert.Equal(5, resultado);
    }
}

Pruebas Basadas en Datos (Data-Driven Tests)

XUnit permite escribir una sola prueba que se ejecute con múltiples conjuntos de datos usando [Theory] y uno de los atributos de datos:

[InlineData]

Para datos simples y fijos:

[Theory]
[InlineData(1, 2, 3)]
[InlineData(-1, -1, -2)]
[InlineData(0, 0, 0)]
public void Sumar_VariosCasos_DevuelveResultadoEsperado(int a, int b, int esperado)
{
    var calc = new Calculadora();
    var resultado = calc.Sumar(a, b);
    Assert.Equal(esperado, resultado);
}

[MemberData]

Para conjuntos de datos definidos en una propiedad o método estático:

public static IEnumerable<object[]> DatosSuma =>
    new List<object[]>
    {
        new object[] { 1, 2, 3 },
        new object[] { -1, -1, -2 },
        new object[] { 0, 0, 0 }
    };

[Theory]
[MemberData(nameof(DatosSuma))]
public void Sumar_DatosDesdeMember_DevuelveResultado(int a, int b, int esperado)
{
    var calc = new Calculadora();
    var resultado = calc.Sumar(a, b);
    Assert.Equal(esperado, resultado);
}

[ClassData]

Para lógica de generación de datos más compleja, implementando IEnumerable<object[]>:

public class DatosCalculadora : IEnumerable<object[]>
{
    public IEnumerator<object[]> GetEnumerator()
    {
        yield return new object[] { 2, 3, 5 };
        yield return new object[] { 10, -5, 5 };
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

[Theory]
[ClassData(typeof(DatosCalculadora))]
public void Sumar_DatosDesdeClase_DevuelveResultado(int a, int b, int esperado)
{
    var calc = new Calculadora();
    var resultado = calc.Sumar(a, b);
    Assert.Equal(esperado, resultado);
}

Uso de Fixtures Compartidas

Para compartir la configuración entre múltiples pruebas dentro de una clase, implementa IClassFixture<T>:

public class DatabaseFixture : IDisposable
{
    public DatabaseFixture()
    {
        // Configuración de la base de datos (por ejemplo, en memoria)
        Db = new List<string> { "dato1", "dato2" };
    }

    public List<string> Db { get; private set; }

    public void Dispose()
    {
        // Limpieza
    }
}

public class DatabaseTests : IClassFixture<DatabaseFixture>
{
    private readonly DatabaseFixture _fixture;

    public DatabaseTests(DatabaseFixture fixture)
    {
        _fixture = fixture;
    }

    [Fact]
    public void ObtenerDatos_Existen_DevuelveLista()
    {
        var datos = _fixture.Db;
        Assert.Contains("dato1", datos);
    }
}

Mocks e Integración con Moq

Combina XUnit con Moq para aislar dependencias:

dotnet add package Moq
using Moq;
using Xunit;

public class ServicioNotificacionesTests
{
    [Fact]
    public void Enviar_ClienteValido_EnviaCorreo()
    {
        // Arrange
        var mockCliente = new Mock<IClienteCorreo>();
        var servicio = new ServicioNotificaciones(mockCliente.Object);

        // Act
        servicio.Enviar("[email protected]", "Asunto", "Cuerpo");

        // Assert
        mockCliente.Verify(c => c.EnviarCorreo(
            "[email protected]", "Asunto", "Cuerpo"
        ), Times.Once);
    }
}

Buenas Prácticas

  1. Nombres descriptivos: Usa nombres de método que describan el escenario y el resultado esperado (ej. Sumar_NumerosPositivos_DevuelveSuma).

  2. Una aserción por prueba (cuando sea posible): Facilita la localización de fallos.

  3. Evita lógica en las pruebas: Las pruebas deben ser simples y predecibles.

  4. Pruebas independientes: Cada prueba debe poder ejecutarse de forma aislada.

  5. Usa [Trait] para categorizar: Permite filtrar pruebas en CI/CD.

    [Fact]
    [Trait("Categoria", "Unitarias")]
    public void PruebaRapida() { }
    

Ejecución de Pruebas

Desde la terminal:

dotnet test

Para filtrar por categoría:

dotnet test --filter "Categoria=Unitarias"

Recursos Adicionales

Contribuciones

Si deseas contribuir a este skill, por favor revisa las guías de contribución en el repositorio original.

Individual skills in this repo

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

github/acquire-codebase-knowledge

Use this skill when the user explicitly asks to map, document, or onboard into an existing codebase. Trigger for prompts like "map this codebase", "document this architecture", "onboard me to this repo", or "create codebase docs". Do not trigger for routine feature implementation, bug fixes, or narrow code edits unless the user asks for repository-level discovery.

github/add-educational-comments

Add educational comments to the file specified, or prompt asking for file to comment if one is not provided.

github/agent-governance

Patterns and techniques for adding governance, safety, and trust controls to AI agent systems. Use this skill when: - Building AI agents that call external tools (APIs, databases, file systems) - Implementing policy-based access controls for agent tool usage - Adding semantic intent classification to detect dangerous prompts - Creating trust scoring systems for multi-agent workflows - Building audit trails for agent actions and decisions - Enforcing rate limits, content filters, or tool restrictions on agents - Working with any agent framework (PydanticAI, CrewAI, OpenAI Agents, LangChain, AutoGen)

github/agentic-eval

Patterns and techniques for evaluating and improving AI agent outputs. Use this skill when: - Implementing self-critique and reflection loops - Building evaluator-optimizer pipelines for quality-critical generation - Creating test-driven code refinement workflows - Designing rubric-based or LLM-as-judge evaluation systems - Adding iterative improvement to agent outputs (code, reports, analysis) - Measuring and improving agent response quality

github/agent-owasp-compliance

Check any AI agent codebase against the OWASP Agentic Security Initiative (ASI) Top 10 risks. Use this skill when: - Evaluating an agent system's security posture before production deployment - Running a compliance check against OWASP ASI 2026 standards - Mapping existing security controls to the 10 agentic risks - Generating a compliance report for security review or audit - Comparing agent framework security features against the standard - Any request like "is my agent OWASP compliant?", "check ASI compliance", or "agentic security audit"

github/ai-prompt-engineering-safety-review

Comprehensive AI prompt engineering safety review and improvement prompt. Analyzes prompts for safety, bias, security vulnerabilities, and effectiveness while providing detailed improvement recommendations with extensive frameworks, testing methodologies, and educational content.

github/appinsights-instrumentation

Instrument a webapp to send useful telemetry data to Azure App Insights

github/apple-appstore-reviewer

Serves as a reviewer of the codebase with instructions on looking for Apple App Store optimizations or rejection reasons.

github/architecture-blueprint-generator

Comprehensive project architecture blueprint generator that analyzes codebases to create detailed architectural documentation. Automatically detects technology stacks and architectural patterns, generates visual diagrams, documents implementation patterns, and provides extensible blueprints for maintaining architectural consistency and guiding new development.

github/arch-linux-triage

Triage and resolve Arch Linux issues with pacman, systemd, and rolling-release best practices.

github/arize-ai-provider-integration

Creates, reads, updates, and deletes Arize AI integrations that store LLM provider credentials used by evaluators and other Arize features. Supports any LLM provider (e.g. OpenAI, Anthropic, Azure OpenAI, AWS Bedrock, Vertex AI, Gemini, NVIDIA NIM). Use when the user mentions AI integration, LLM provider credentials, create integration, list integrations, update credentials, delete integration, or connecting an LLM provider to Arize.

github/arize-annotation

Creates and manages annotation configs (categorical, continuous, freeform label schemas) and annotation queues (human review workflows) on Arize. Applies human annotations to project spans via the Python SDK. Use when the user mentions annotation config, annotation queue, label schema, human feedback, bulk annotate spans, update_annotations, labeling queue, annotate record, or human review.

github/arize-dataset

Creates, manages, and queries Arize datasets and examples. Covers dataset CRUD, appending examples, exporting data, and file-based dataset creation using the ax CLI. Use when the user needs test data, evaluation examples, or mentions create dataset, list datasets, export dataset, append examples, dataset version, golden dataset, or test set.

github/arize-evaluator

Handles LLM-as-judge evaluation workflows on Arize including creating/updating evaluators, running evaluations on spans or experiments, managing tasks, trigger-run operations, column mapping, and continuous monitoring. Use when the user mentions create evaluator, LLM judge, hallucination, faithfulness, correctness, relevance, run eval, score spans, score experiment, trigger-run, column mapping, continuous monitoring, or improve evaluator prompt.

github/arize-experiment

Creates, runs, and analyzes Arize experiments for evaluating and comparing model performance. Covers experiment CRUD, exporting runs, comparing results, and evaluation workflows using the ax CLI. Use when the user mentions create experiment, run experiment, compare models, model performance, evaluate AI, experiment results, benchmark, A/B test models, or measure accuracy.

github/arize-instrumentation

Adds Arize AX tracing to an LLM application for the first time. Follows a two-phase agent-assisted flow to analyze the codebase then implement instrumentation after user confirmation. Use when the user wants to instrument their app, add tracing from scratch, set up LLM observability, integrate OpenTelemetry or openinference, or get started with Arize tracing.

github/arize-link

Generates deep links to the Arize UI for traces, spans, sessions, datasets, labeling queues, evaluators, and annotation configs. Produces clickable URLs for sharing Arize resources with team members. Use when the user wants to link to or open a trace, span, session, dataset, evaluator, or annotation config in the Arize UI.

github/arize-prompt-optimization

Optimizes, improves, and debugs LLM prompts using production trace data, evaluations, and annotations. Extracts prompts from spans, gathers performance signal, and runs a data-driven optimization loop using the ax CLI. Use when the user mentions optimize prompt, improve prompt, make AI respond better, improve output quality, prompt engineering, prompt tuning, or system prompt improvement.

github/arize-trace

Downloads, exports, and inspects existing Arize traces and spans to understand what an LLM app is doing or debug runtime issues. Covers exporting traces by ID, spans by ID, sessions by ID, and root-cause investigation using the ax CLI. Use when the user wants to look at existing trace data, see what their LLM app is doing, export traces, download spans, investigate errors, or analyze behavior regressions.

github/aspire

Aspire skill covering the Aspire CLI, AppHost orchestration, service discovery, integrations, MCP server, VS Code extension, Dev Containers, GitHub Codespaces, templates, dashboard, and deployment. Use when the user asks to create, run, debug, configure, deploy, or troubleshoot an Aspire distributed application.

Skills relacionados