Community程式設計與開發github.com

快照測試

在 .NET 中使用 Verify 進行快照測試。核准 API 表面、HTTP 回應、渲染的電子郵件和序列化輸出。透過人工審查的基準檔案偵測非預期的變更。

快照測試 是什麼?

這個技能教導開發者如何使用 Verify 函式庫在 .NET 專案中實作快照測試。快照測試會捕捉程式輸出,並將其與人工核准的基準檔案進行比較,以偵測非預期的變更。它支援多種測試框架(xUnit、NUnit、MSTest),並可應用於測試渲染的 HTML/電子郵件、核准公共 API 表面(透過 PublicApiGenerator)、驗證 HTTP 回應以及驗證序列化物件。技能中詳細說明了安裝與設定、清理動態值(如 GUID 和時間戳)、檔案組織最佳實踐以及 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 進行快照測試

何時使用此技能

在以下情況下使用快照測試:

  • 驗證渲染輸出(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

# 將 verified 檔案視為產生的(在 PR 差異中摺疊)
*.verified.txt linguist-generated=true
*.verified.html linguist-generated=true
*.verified.json linguist-generated=true

CI/CD 整合

缺少 Verified 檔案時失敗

[ModuleInitializer]
public static void Init()
{
    // 在 CI 中,失敗而不是啟動差異工具
    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.*

何時使用快照測試

情境使用快照測試?原因
渲染的 HTML/電子郵件是捕捉視覺回歸
API 表面是防止意外破損
序列化輸出是驗證傳輸格式
複雜物件圖形是比手動斷言更容易
簡單數值檢查否使用一般斷言
商業邏輯否使用明確斷言
效能測試否使用基準測試

最佳實踐

應該做

// 使用描述性測試名稱 - 它們會成為檔案名稱
[Fact]
public Task UserRegistration_WithValidData_ReturnsConfirmation()

// 一致地清除動態值
VerifierSettings.ScrubMembersWithType<Guid>();

// 針對非文字內容使用副檔名參數
await Verify(html, extension: "html");

// 將 verified 檔案保留在原始碼控制中
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.

相關技能