Community编程与开发github.com

快照测试(Snapshot Testing)

使用 Verify 在 .NET 中进行快照测试。批准 API 接口、HTTP 响应、渲染的邮件以及序列化输出。通过人工审核的基线文件检测意外变更。

快照测试(Snapshot Testing) 是什么?

该技能详细介绍如何在 .NET 项目中利用 Verify 库执行快照测试(Snapshot Testing),以替代传统的断言验证方式。它适用于验证渲染输出(如 HTML 邮件、报告)、批准公共 API 接口、测试 HTTP 响应体及头文件、验证序列化结果以及捕获复杂对象中的意外变更。技能文档涵盖了安装配置(支持 XUnit、NUnit、MSTest 框架)、基本用法(验证简单对象、字符串/HTML)、特定场景实践(邮件模板测试、API 接口审批、HTTP 响应测试)以及处理动态数据(如 GUID、时间戳)的清洗(Scrubbing)技巧。此外,还提供了文件组织建议、CI/CD 集成指导(如 GitHub Actions)和最佳实践列表。该技能特别适合需要确保输出一致性和尽早发现回归问题的开发团队。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/snapshot-testing

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

使用 Verify 进行快照测试(Snapshot Testing)

何时使用该技能

在以下场景中使用快照测试:

  • 验证渲染输出(HTML 邮件、报告、生成的代码)
  • 批准公共 API 接口以检测破坏性变更
  • 测试 HTTP 响应体和头文件
  • 验证序列化输出
  • 捕获复杂对象中的意外变更

什么是快照测试?

快照测试捕获输出并将其与人工批准的基线进行比较:

  1. 首次运行:测试生成一个 .received. 文件,包含实际输出
  2. 人工审核:开发者批准该文件,创建 .verified. 文件
  3. 后续运行:测试将输出与 .verified. 文件进行比较
  4. 检测到变更:测试失败,差异工具显示差异供审核

这可以捕获意外变更,同时通过明确批准允许有意变更。


安装

添加 Verify 包

dotnet add package Verify.Xunit
# 或其他测试框架:
dotnet add package Verify.NUnit
dotnet add package Verify.MSTest

配置 ModuleInitializer

在测试项目中创建一个 ModuleInitializer.cs 文件:

using System.Runtime.CompilerServices;

public static class ModuleInitializer
{
    [ModuleInitializer]
    public static void Init()
    {
        // 使用源文件相对路径存储已验证文件
        VerifyBase.UseProjectRelativeDirectory("Snapshots");

        // 配置差异工具(可选 - 自动检测)
        // DiffTools.UseOrder(DiffTool.Rider, DiffTool.VisualStudioCode);
    }
}

基本用法

简单对象验证

[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);
}

创建 VerifyUserDto.verified.txt:

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

字符串/HTML 验证

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

    // 使用扩展参数确保文件命名正确
    await Verify(html, extension: "html");
}

创建 VerifyRenderedEmail.verified.html - 可在浏览器中查看。


电子邮件模板测试

使用 Verify 捕获渲染电子邮件模板中的意外变更:

[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");
}

电子邮件测试的好处:

  • 捕获 CSS/布局回归问题
  • 检测模板变量是否失效
  • 在差异工具中进行视觉审核
  • 版本控制跟踪邮件变更

API 接口审批

防止对公共 API 进行意外的破坏性变更:

[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);
}

或者使用专用的 ApiApprover 包:

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

创建包含完整 API 接口的 .verified.txt 文件 - 任何变更都需要明确批准。


HTTP 响应测试

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

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

    // 同时验证状态码、头文件和体
    await Verify(new
    {
        StatusCode = response.StatusCode,
        Headers = response.Headers
            .Where(h => h.Key.StartsWith("X-"))  // 仅限自定义头文件
            .ToDictionary(h => h.Key, h => h.Value.First()),
        Body = await response.Content.ReadAsStringAsync()
    });
}

清洗动态值

处理时间戳、GUID 和其他动态内容:

[Fact]
public Task VerifyOrder()
{
    var order = new Order
    {
        Id = Guid.NewGuid(),  // 每次运行都不同
        CreatedAt = DateTime.UtcNow,  // 每次运行都不同
        Total = 99.99m
    };

    return Verify(order)
        .ScrubMember("Id")  // 替换为占位符
        .ScrubMember("CreatedAt");
}

输出:

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

全局清洗

在 ModuleInitializer 中配置:

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

    // 清洗特定模式
    VerifierSettings.AddScrubber(s =>
        Regex.Replace(s, @"token=[a-zA-Z0-9]+", "token=SCRUBBED"));
}

文件组织

推荐结构

tests/
  MyApp.Tests/
    Snapshots/           # 所有已验证文件
      EmailTests/
        WelcomeEmail.verified.html
        PasswordReset.verified.html
      ApiTests/
        GetUser.verified.txt
    EmailTests.cs
    ApiTests.cs
    ModuleInitializer.cs

.gitignore

# Verify - 忽略 received 文件(仅提交 verified 文件)
*.received.*

.gitattributes

# 将已验证文件视为生成文件(在 PR 差异中折叠)
*.verified.txt linguist-generated=true
*.verified.html linguist-generated=true
*.verified.json linguist-generated=true

CI/CD 集成

缺失已验证文件时失败

[ModuleInitializer]
public static void Init()
{
    // 在 CI 环境中,失败而不是启动差异工具
    if (Environment.GetEnvironmentVariable("CI") == "true")
    {
        VerifyDiffPlex.UseDiffPlex(OutputType.Minimal);
        DiffRunner.Disabled = true;
    }
}

GitHub Actions

- name: 运行测试
  run: dotnet test
  env:
    CI: true

- name: 失败时上传快照
  if: failure()
  uses: actions/upload-artifact@v4
  with:
    name: snapshots
    path: |
      **/*.received.*
      **/*.verified.*

何时使用快照测试

场景使用快照测试?原因
渲染的 HTML/邮件是捕获视觉回归问题
API 接口是防止意外破坏
序列化输出是验证线路格式
复杂对象图是比手动断言更简单
简单值检查否使用常规断言
业务逻辑否使用显式断言
性能测试否使用基准测试

最佳实践

应该做的

// 使用描述性测试名称 - 它们会成为文件名
[Fact]
public Task UserRegistration_WithValidData_ReturnsConfirmation()

// 一致地清洗动态值
VerifierSettings.ScrubMembersWithType<Guid>();

// 对非文本内容使用扩展参数
await Verify(html, extension: "html");

// 将已验证文件保存在源代码控制中
git add *.verified.*

不应该做的

// 不要验证未经清洗的随机/动态数据
var order = new Order { Id = Guid.NewGuid() };  // 每次运行都失败!
await Verify(order);

// 不要提交 .received 文件
git add *.received.*  // 错误!

// 不要用于简单断言
await Verify(result.Count);  // 只需使用 Assert.Equal(5, result.Count)

与 MJML 邮件测试集成

请参阅 aspnetcore/transactional-emails 技能以获取完整模式:

  1. 包含 {{variable}} 占位符的 MJML 模板
  2. 使用测试数据渲染为 HTML
  3. 对渲染输出进行快照测试
  4. 在批准之前在差异工具中审核更改

这可以捕获:

  • 变量替换失效
  • CSS/布局回归问题
  • 邮件客户端兼容性问题
  • 意外的内容变更

资源

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.

相关技能