Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问clear审计通过

dotnet-testing-complex-object-comparisondotnet 测试复杂对象比较

Agent Skill

用于辅助测试设计、自动化测试、用例整理和回归验证。它适合让 Agent 编写单元测试、端到端测试、测试计划或根据失败日志定位问题。使用时需要确认项目测试框架、运行命令和夹具数据,避免为了通过测试而改坏真实逻辑;涉及浏览器或外部服务时,应区分本地模拟、测试环境和生产环境。

总安装

699

周安装

28

GitHub Stars

24

下载量

226
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:dotnet-testing-complex-object-comparison(dotnet 测试复杂对象比较)
来源仓库:https://github.com/kevintsengtw/dotnet-testing-agent-skills
仓库路径:skills/dotnet-testing-complex-object-comparison
安装命令:
npx skills add https://github.com/kevintsengtw/dotnet-testing-agent-skills --skill dotnet-testing-complex-object-comparison
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/kevintsengtw/dotnet-testing-agent-skills --skill dotnet-testing-complex-object-comparison

简介

dotnet-testing-complex-object-comparison 实现深层嵌套对象的递归等价性比对。

  • 支持 Customer.Address.City 等多级属性路径的精确匹配验证。
  • 忽略指定字段(如 Id)同时保留业务关键字段的严格校验。
  • 需引入 Should().BeEquivalentTo() 方法并配置忽略规则。
  • 适用于 DTO 往返转换、缓存重建或 API 响应结构一致性检查。

SKILL.md

複雜物件比對指南(Complex Object Comparison)

核心使用場景

1. 深層物件結構比對 (Object Graph Comparison)

當需要比對包含多層巢狀屬性的複雜物件時:

[Fact]
public void ComplexObject_深層結構比對_應完全相符()
{
    var expected = new Order
    {
        Id = 1,
        Customer = new Customer
        {
            Name = "John Doe",
            Address = new Address
            {
                Street = "123 Main St",
                City = "Seattle",
                ZipCode = "98101"
            }
        },
        Items = new[]
        {
            new OrderItem { ProductName = "Laptop", Quantity = 1, Price = 999.99m },
            new OrderItem { ProductName = "Mouse", Quantity = 2, Price = 29.99m }
        }
    };

    var actual = orderService.GetOrder(1);

    // 深層物件比對
    actual.Should().BeEquivalentTo(expected);
}

2. 循環參照處理 (Circular Reference Handling)

處理物件之間存在循環參照的情況:

[Fact]
public void TreeStructure_循環參照_應正確處理()
{
    // 建立具有父子雙向參照的樹狀結構
    var parent = new TreeNode { Value = "Root" };
    var child1 = new TreeNode { Value = "Child1", Parent = parent };
    var child2 = new TreeNode { Value = "Child2", Parent = parent };
    parent.Children = new[] { child1, child2 };

    var actualTree = treeService.GetTree("Root");

    // 處理循環參照
    actualTree.Should().BeEquivalentTo(parent, options =>
        options.IgnoringCyclicReferences()
               .WithMaxRecursionDepth(10)
    );
}

3-6. 進階比對模式

AwesomeAssertions 還提供多種進階比對模式:動態欄位排除(排除時間戳記、自動生成欄位)、巢狀物件欄位排除、大量資料效能最佳化比對(選擇性屬性比對、抽樣驗證策略)、以及嚴格/寬鬆排序控制。

完整程式碼範例請參閱 references/detailed-comparison-patterns.md

比對選項速查表

選項方法用途適用場景
Excluding(x => x.Property)排除特定屬性排除時間戳記、自動生成欄位
Including(x => x.Property)只包含特定屬性關鍵屬性驗證
IgnoringCyclicReferences()忽略循環參照樹狀結構、雙向關聯
WithMaxRecursionDepth(n)限制遞迴深度深層巢狀結構
WithStrictOrdering()嚴格順序比對陣列/集合順序重要時
WithoutStrictOrdering()寬鬆順序比對陣列/集合順序不重要時
WithTracing()啟用追蹤除錯複雜比對失敗

常見比對模式與解決方案

模式 1:Entity Framework 實體比對

[Fact]
public void EFEntity_資料庫實體_應排除導航屬性()
{
    var expected = new Product { Id = 1, Name = "Laptop", Price = 999 };
    var actual = dbContext.Products.Find(1);

    actual.Should().BeEquivalentTo(expected, options =>
        options.ExcludingMissingMembers()  // 排除 EF 追蹤屬性
               .Excluding(p => p.CreatedAt)
               .Excluding(p => p.UpdatedAt)
    );
}

模式 2:API Response 比對

[Fact]
public void ApiResponse_JSON反序列化_應忽略額外欄位()
{
    var expected = new UserDto
    {
        Id = 1,
        Username = "john_doe"
    };

    var response = await httpClient.GetAsync("/api/users/1");
    var actual = await response.Content.ReadFromJsonAsync<UserDto>();

    actual.Should().BeEquivalentTo(expected, options =>
        options.ExcludingMissingMembers()  // 忽略 API 額外欄位
    );
}

模式 3:測試資料建構器比對

[Fact]
public void Builder_測試資料_應匹配預期結構()
{
    var expected = new OrderBuilder()
        .WithId(1)
        .WithCustomer("John Doe")
        .WithItems(3)
        .Build();

    var actual = orderService.CreateOrder(orderRequest);

    actual.Should().BeEquivalentTo(expected, options =>
        options.Excluding(o => o.OrderNumber)  // 系統生成
               .Excluding(o => o.CreatedAt)
    );
}

錯誤訊息最佳化

提供有意義的錯誤訊息

[Fact]
public void Comparison_錯誤訊息_應清楚說明差異()
{
    var expected = new User { Name = "John", Age = 30 };
    var actual = userService.GetUser(1);

    // 使用 because 參數提供上下文
    actual.Should().BeEquivalentTo(expected, options =>
        options.Excluding(u => u.Id)
               .Because("ID 是系統自動生成的,不應納入比對")
    );
}

使用 AssertionScope 進行批次驗證

[Fact]
public void MultipleComparisons_批次驗證_應一次顯示所有失敗()
{
    var users = userService.GetAllUsers();

    using (new AssertionScope())
    {
        foreach (var user in users)
        {
            user.Id.Should().BeGreaterThan(0);
            user.Name.Should().NotBeNullOrEmpty();
            user.Email.Should().MatchRegex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
        }
    }
    // 所有失敗會一起報告,而非遇到第一個失敗就停止
}

與其他技能整合

此技能可與以下技能組合使用:

  • awesome-assertions-guide: 基礎斷言語法與常用 API
  • autofixture-data-generation: 自動生成測試資料
  • test-data-builder-pattern: 建構複雜測試物件
  • unit-test-fundamentals: 單元測試基礎與 3A 模式

最佳實踐建議

推薦做法

  1. 優先使用屬性排除而非包含:除非只需驗證少數屬性,否則使用 Excluding 更清楚
  2. 建立可重用的排除擴充方法:避免在每個測試重複排除邏輯
  3. 為大量資料比對設定合理策略:平衡效能與驗證完整性
  4. 使用 AssertionScope 進行批次驗證:一次看到所有失敗原因
  5. 提供有意義的 because 說明:幫助未來維護者理解測試意圖

避免做法

  1. 避免過度依賴完整物件比對:考慮只驗證關鍵屬性
  2. 避免忽略循環參照問題:使用 IgnoringCyclicReferences() 明確處理
  3. 避免在每個測試重複排除邏輯:提取為擴充方法
  4. 避免對大量資料做完整深度比對:使用抽樣或關鍵屬性驗證

疑難排解

Q1: BeEquivalentTo 效能很慢怎麼辦?

A: 使用以下策略優化:

  • 使用 Including 只比對關鍵屬性
  • 對大量資料採用抽樣驗證
  • 使用 WithMaxRecursionDepth 限制遞迴深度
  • 考慮使用 AssertKeyPropertiesOnly 快速比對關鍵欄位

Q2: 如何處理 StackOverflowException?

A: 通常由循環參照引起:

options.IgnoringCyclicReferences()
       .WithMaxRecursionDepth(10)

Q3: 如何排除所有時間相關欄位?

A: 使用路徑模式匹配:

options.Excluding(ctx => ctx.Path.EndsWith("At"))
       .Excluding(ctx => ctx.Path.EndsWith("Time"))
       .Excluding(ctx => ctx.Path.Contains("Timestamp"))

Q4: 比對失敗但看不出差異?

A: 啟用詳細追蹤:

options.WithTracing()  // 產生詳細的比對追蹤資訊

範本檔案參考

本技能提供以下範本檔案:

  • templates/comparison-patterns.cs: 常見比對模式範例
  • templates/exclusion-strategies.cs: 欄位排除策略與擴充方法

輸出格式

  • 產生使用 BeEquivalentTo 的深層物件比對斷言
  • 包含 Excluding/Including 屬性過濾設定
  • 務必提及循環參照處理:即使使用者未明確問到,也應說明 IgnoringCyclicReferences()WithMaxRecursionDepth(n) 的用法,因為深層巢狀物件經常會遇到循環參照問題
  • 包含 DTO/Entity 比對的完整測試程式碼

參考資源

原始文章

本技能內容提煉自「老派軟體工程師的測試修練 - 30 天挑戰」系列文章:

  • Day 05 - AwesomeAssertions 進階技巧與複雜情境應用

- 鐵人賽文章:https://ithelp.ithome.com.tw/articles/10374425 - 範例程式碼:https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day05

官方文件

相關技能

  • awesome-assertions-guide - AwesomeAssertions 基礎與進階用法
  • unit-test-fundamentals - 單元測試基礎

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

29.02%
按下载量换算66

Gemini CLI

25.38%
按下载量换算57

Antigravity

16.08%
按下载量换算36

OpenCode

13.67%
按下载量换算31

windsurf

8.7%
按下载量换算20

github-copilot

3.78%
按下载量换算9

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills