CommunityProgramación y desarrollogithub.com

Pruebas de Instantáneas (Snapshot Testing)

Utiliza Verify para realizar pruebas de instantáneas en .NET. Aprueba superficies de API, respuestas HTTP, correos electrónicos renderizados y salidas serializadas. Detecta cambios no intencionados mediante archivos de referencia revisados por humanos.

¿Qué es Pruebas de Instantáneas (Snapshot Testing)?

Esta habilidad dota al agente de la capacidad de implementar y gestionar pruebas de instantáneas (snapshot testing) con la librería Verify en proyectos .NET. Es esencial para desarrolladores que necesitan asegurar la estabilidad de salidas complejas como renderizados HTML, superficies de API, respuestas HTTP y objetos serializados, ya que permite detectar cambios no intencionados mediante la comparación contra archivos de referencia aprobados por humanos. Funciona con los frameworks de pruebas más populares (xUnit, NUnit, MSTest) y se integra a la perfección con flujos CI/CD como GitHub Actions. El agente puede configurar Verify desde cero, crear pruebas de instantáneas para diversos escenarios (correos electrónicos, API, objetos), y aplicar estrategias de 'limpieza' (scrubbing) para manejar valores dinámicos como GUIDs y marcas de tiempo, garantizando pruebas fiables y repetibles. Además, la habilidad cubre la organización de archivos, la configuración de .gitignore y .gitattributes, y las mejores prácticas para evitar falsos positivos y mantener una alta calidad en el código.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/snapshot-testing

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

Pruebas de Instantáneas con Verify

Cuándo Usar Esta Habilidad

Utiliza pruebas de instantáneas cuando:

  • Verifiques salidas renderizadas (correos HTML, informes, código generado)
  • Apruebes superficies de API públicas para detectar cambios disruptivos
  • Pruebes cuerpos y cabeceras de respuestas HTTP
  • Valides resultados de serialización
  • Detectes cambios no intencionados en objetos complejos

¿Qué son las Pruebas de Instantáneas?

Las pruebas de instantáneas capturan la salida y la comparan con una línea base aprobada por humanos:

  1. Primera ejecución: La prueba genera un archivo .received. con la salida real
  2. Revisión humana: El desarrollador lo aprueba, creando un archivo .verified.
  3. Ejecuciones posteriores: La prueba compara la salida con el archivo .verified.
  4. Cambios detectados: La prueba falla, una herramienta de diferencias muestra los cambios para revisión

Esto detecta cambios no intencionados permitiendo cambios intencionados mediante aprobación explícita.


Instalación

Agregar el Paquete Verify

dotnet add package Verify.Xunit
# o para otros frameworks de prueba:
dotnet add package Verify.NUnit
dotnet add package Verify.MSTest

Configurar ModuleInitializer

Crea un archivo ModuleInitializer.cs en tu proyecto de pruebas:

using System.Runtime.CompilerServices;

public static class ModuleInitializer
{
    [ModuleInitializer]
    public static void Init()
    {
        // Usa rutas relativas al archivo fuente para los archivos verificados
        VerifyBase.UseProjectRelativeDirectory("Snapshots");

        // Configura la herramienta de diferencias (opcional - se detecta automáticamente)
        // DiffTools.UseOrder(DiffTool.Rider, DiffTool.VisualStudioCode);
    }
}

Uso Básico

Verificación de Objeto Simple

[Fact]
public Task VerifyUserDto()
{
    var user = new UserDto(
        Id: "user-123",
        Name: "John Doe",
        Email: "[email protected]",
        CreatedAt: new DateTime(2025, 1, 15));

    return Verify(user);
}

Crea VerifyUserDto.verified.txt:

{
  Id: user-123,
  Name: John Doe,
  Email: [email protected],
  CreatedAt: 2025-01-15T00:00:00
}

Verificación de Cadenas/HTML

[Fact]
public async Task VerifyRenderedEmail()
{
    var html = await _emailRenderer.RenderAsync("Welcome", new { Name = "John" });

    // Usa el parámetro extension para un nombre de archivo adecuado
    await Verify(html, extension: "html");
}

Crea VerifyRenderedEmail.verified.html - visible en el navegador.


Pruebas de Plantillas de Correo Electrónico

Usa Verify para detectar cambios no intencionados en plantillas de correo renderizadas:

[Fact]
public async Task UserSignupInvitation_RendersCorrectly()
{
    var renderer = _services.GetRequiredService<IMjmlTemplateRenderer>();

    var variables = new Dictionary<string, string>
    {
        { "OrganizationName", "Acme Corporation" },
        { "InviteeName", "John Doe" },
        { "InviterName", "Jane Admin" },
        { "InvitationLink", "https://example.com/invite/abc123" },
        { "ExpirationDate", "December 31, 2025" }
    };

    var html = await renderer.RenderTemplateAsync(
        "UserInvitations/UserSignupInvitation",
        variables);

    await Verify(html, extension: "html");
}

Beneficios para pruebas de correo:

  • Detecta regresiones de CSS/maquetación
  • Encuentra variables de plantilla rotas
  • Revisión visual en la herramienta de diferencias
  • El control de versiones rastrea cambios en correos

Aprobación de Superficies de API

Prevén cambios disruptivos accidentales en APIs públicas:

[Fact]
public Task ApprovePublicApi()
{
    var assembly = typeof(MyLibrary.PublicClass).Assembly;

    var publicApi = assembly.GetExportedTypes()
        .OrderBy(t => t.FullName)
        .Select(t => new
        {
            Type = t.FullName,
            Members = t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
                .Where(m => m.DeclaringType == t)
                .OrderBy(m => m.Name)
                .Select(m => m.ToString())
        });

    return Verify(publicApi);
}

O usa el paquete dedicado ApiApprover:

dotnet add package PublicApiGenerator
dotnet add package Verify.Xunit
[Fact]
public Task ApproveApi()
{
    var api = typeof(MyPublicClass).Assembly.GeneratePublicApi();
    return Verify(api);
}

Crea un archivo .verified.txt con la superficie completa de la API - cualquier cambio requiere aprobación explícita.


Pruebas de Respuestas HTTP

[Fact]
public async Task GetUser_ReturnsExpectedResponse()
{
    var client = _factory.CreateClient();

    var response = await client.GetAsync("/api/users/123");

    // Verifica estado, cabeceras y cuerpo juntos
    await Verify(new
    {
        StatusCode = response.StatusCode,
        Headers = response.Headers
            .Where(h => h.Key.StartsWith("X-"))  // Solo cabeceras personalizadas
            .ToDictionary(h => h.Key, h => h.Value.First()),
        Body = await response.Content.ReadAsStringAsync()
    });
}

Limpieza de Valores Dinámicos

Maneja marcas de tiempo, GUIDs y otro contenido dinámico:

[Fact]
public Task VerifyOrder()
{
    var order = new Order
    {
        Id = Guid.NewGuid(),  // Diferente en cada ejecución
        CreatedAt = DateTime.UtcNow,  // Diferente en cada ejecución
        Total = 99.99m
    };

    return Verify(order)
        .ScrubMember("Id")  // Reemplaza con un marcador de posición
        .ScrubMember("CreatedAt");
}

Salida:

{
  Id: Guid_1,
  CreatedAt: DateTime_1,
  Total: 99.99
}

Limpieza Global

Configura en ModuleInitializer:

[ModuleInitializer]
public static void Init()
{
    VerifierSettings.ScrubMembersWithType<DateTime>();
    VerifierSettings.ScrubMembersWithType<DateTimeOffset>();
    VerifierSettings.ScrubMembersWithType<Guid>();

    // Limpia patrones específicos
    VerifierSettings.AddScrubber(s =>
        Regex.Replace(s, @"token=[a-zA-Z0-9]+", "token=SCRUBBED"));
}

Organización de Archivos

Estructura Recomendada

tests/
  MyApp.Tests/
    Snapshots/           # Todos los archivos verificados
      EmailTests/
        WelcomeEmail.verified.html
        PasswordReset.verified.html
      ApiTests/
        GetUser.verified.txt
    EmailTests.cs
    ApiTests.cs
    ModuleInitializer.cs

.gitignore

# Verify - ignora archivos recibidos (solo confirmar los verificados)
*.received.*

.gitattributes

# Trata los archivos verificados como generados (colapsar en diferencias de PR)
*.verified.txt linguist-generated=true
*.verified.html linguist-generated=true
*.verified.json linguist-generated=true

Integración con CI/CD

Fallar si Faltan Archivos Verificados

[ModuleInitializer]
public static void Init()
{
    // En CI, falla en lugar de lanzar la herramienta de diferencias
    if (Environment.GetEnvironmentVariable("CI") == "true")
    {
        VerifyDiffPlex.UseDiffPlex(OutputType.Minimal);
        DiffRunner.Disabled = true;
    }
}

GitHub Actions

- name: Run tests
  run: dotnet test
  env:
    CI: true

- name: Upload snapshots on failure
  if: failure()
  uses: actions/upload-artifact@v4
  with:
    name: snapshots
    path: |
      **/*.received.*
      **/*.verified.*

Cuándo Usar Pruebas de Instantáneas

Escenario¿Usar Pruebas de Instantáneas?Por qué
HTML/correos renderizadosSíDetecta regresiones visuales
Superficies de APISíPreviene roturas accidentales
Salida de serializaciónSíValida el formato de transmisión
Gráficos de objetos complejosSíMás fácil que aserciones manuales
Verificaciones de valores simplesNoUsa aserciones regulares
Lógica de negocioNoUsa aserciones explícitas
Pruebas de rendimientoNoUsa benchmarks

Mejores Prácticas

HACER

// Usa nombres de prueba descriptivos - se convierten en nombres de archivo
[Fact]
public Task UserRegistration_WithValidData_ReturnsConfirmation()

// Limpia valores dinámicos de forma consistente
VerifierSettings.ScrubMembersWithType<Guid>();

// Usa el parámetro extension para contenido que no es texto
await Verify(html, extension: "html");

// Mantén los archivos verificados en control de versiones
git add *.verified.*

NO HACER

// No verifiques datos aleatorios/dinámicos sin limpiar
var order = new Order { Id = Guid.NewGuid() };  // ¡Falla en cada ejecución!
await Verify(order);

// No confirmes archivos .received
git add *.received.*  // ¡Incorrecto!

// No uses para aserciones simples
await Verify(result.Count);  // Solo usa Assert.Equal(5, result.Count)

Integración con Pruebas de Correo MJML

Consulta la habilidad aspnetcore/transactional-emails para el patrón completo:

  1. Plantillas MJML con marcadores de posición {{variable}}
  2. Renderizar a HTML con datos de prueba
  3. Probar con instantáneas la salida renderizada
  4. Revisar cambios en la herramienta de diferencias antes de aprobar

Esto detecta:

  • Sustitución de variables incorrecta
  • Regresiones de CSS/maquetación
  • Problemas de compatibilidad con clientes de correo
  • Cambios no intencionados en el contenido

Recursos

Individual skills in this repo

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

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

Skills relacionados