Dotnet Testing Advanced Tunit Advanced 标志

Dotnet Testing Advanced Tunit Advanced

社区
kevintsengtw
dotnet-testing-advanced-tunit-advanced

TUnit 進階應用完整指南。當需要使用 TUnit 進行資料驅動測試、依賴注入或整合測試時使用。涵蓋 MethodDataSource、ClassDataSource、Matrix Tests、Properties 過濾。包含 Retry/Timeout 控制、WebApplicationFactory 整合、Testcontainers 多服務編排。 Keywords: TUnit advanced, TUnit 進階, MethodDataSource, ClassDataSource, Matrix Tests, MatrixDataSource, MicrosoftDependencyInjectionDataSource, Property, Retry, Timeout, 資料驅動測試, 測試過濾, WebApplicationFactory TUnit, 多容器編排

概览

发布者kevintsengtw
代码仓库dotnet-testing-agent-skills
技能名称dotnet-testing-advanced-tunit-advanced
星标数
30
复刻数
4
附带文件
11
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 11 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 kevintsengtw 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Dotnet Testing Advanced Tunit Advanced AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/kevintsengtw/dotnet-testing-agent-skills/tree/main/skills/dotnet-testing-advanced-tunit-advanced
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/kevintsengtw/dotnet-testing-agent-skills.git /tmp/dotnet-testing-agent-skills
mkdir -p .claude/skills
cp -r /tmp/dotnet-testing-agent-skills/skills/dotnet-testing-advanced-tunit-advanced .claude/skills/dotnet-testing-advanced-tunit-advanced
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Dotnet Testing Advanced Tunit Advanced,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Dotnet Testing Advanced Tunit Advanced。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Dotnet Testing Advanced Tunit Advanced 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

TUnit 進階應用:資料驅動測試、依賴注入與整合測試實戰

資料驅動測試進階技巧

TUnit 提供 MethodDataSource、ClassDataSource、Matrix Tests 三種進階資料來源。MethodDataSource 最靈活,支援動態產生與外部檔案載入;ClassDataSource 適合跨測試類別共享資料與 AutoFixture 整合;Matrix Tests 自動產生所有參數組合(注意控制數量避免爆炸性增長)。

範本使用的 [MatrixDataSource] 自 TUnit 0.7.0 起提供;若使用更早的版本,請改用 [MethodDataSource] 以巢狀迴圈產生參數組合。

完整範例與比較表請參閱 references/data-driven-testing.md


Properties 屬性標記與測試過濾

基本 Properties 使用

csharp
[Test]
[Property("Category", "Database")]
[Property("Priority", "High")]
public async Task DatabaseTest_高優先級_應能透過屬性過濾()
{
    await Assert.That(true).IsTrue();
}

[Test]
[Property("Category", "Unit")]
[Property("Priority", "Medium")]
public async Task UnitTest_中等優先級_基本驗證()
{
    await Assert.That(1 + 1).IsEqualTo(2);
}

[Test]
[Property("Category", "Integration")]
[Property("Priority", "Low")]
[Property("Environment", "Development")]
public async Task IntegrationTest_低優先級_僅開發環境執行()
{
    await Assert.That("Hello World").Contains("World");
}

建立一致的屬性命名規範

csharp
public static class TestProperties
{
    // 測試類別
    public const string CATEGORY_UNIT = "Unit";
    public const string CATEGORY_INTEGRATION = "Integration";
    public const string CATEGORY_E2E = "E2E";

    // 優先級
    public const string PRIORITY_CRITICAL = "Critical";
    public const string PRIORITY_HIGH = "High";
    public const string PRIORITY_MEDIUM = "Medium";
    public const string PRIORITY_LOW = "Low";

    // 環境
    public const string ENV_DEVELOPMENT = "Development";
    public const string ENV_STAGING = "Staging";
    public const string ENV_PRODUCTION = "Production";
}

[Test]
[Property("Category", TestProperties.CATEGORY_UNIT)]
[Property("Priority", TestProperties.PRIORITY_HIGH)]
public async Task ExampleTest_使用常數_確保一致性()
{
    await Assert.That(1 + 1).IsEqualTo(2);
}

TUnit 測試過濾執行

TUnit 使用 dotnet run 而不是 dotnet test:

bash
# 只執行單元測試
dotnet run --treenode-filter "/*/*/*/*[Category=Unit]"

# 只執行高優先級測試
dotnet run --treenode-filter "/*/*/*/*[Priority=High]"

# 組合條件:執行高優先級的單元測試
dotnet run --treenode-filter "/*/*/*/*[(Category=Unit)&(Priority=High)]"

# 或條件:執行單元測試或冒煙測試
dotnet run --treenode-filter "/*/*/*/*[(Category=Unit)|(Suite=Smoke)]"

# 執行特定功能的測試
dotnet run --treenode-filter "/*/*/*/*[Feature=OrderProcessing]"

過濾語法注意事項:

  • 路徑模式 /*/*/*/* 代表 Assembly/Namespace/Class/Method 層級
  • 屬性名稱大小寫敏感
  • 組合條件必須用括號正確包圍

測試生命週期管理

TUnit 提供完整的生命週期鉤子:[Before(Class)] → 建構式 → [Before(Test)] → 測試方法 → [After(Test)] → Dispose → [After(Class)]。另有 Assembly/TestSession 層級與 [BeforeEvery]/[AfterEvery] 全域鉤子。建構式永遠最先執行,BeforeClass/AfterClass 各只執行一次。

完整屬性家族與範例請參閱 references/lifecycle-management.md


依賴注入模式

TUnit 依賴注入核心概念

TUnit 的依賴注入建構在 Data Source Generators 基礎上:

csharp
public class MicrosoftDependencyInjectionDataSourceAttribute : DependencyInjectionDataSourceAttribute<IServiceScope>
{
    private static readonly IServiceProvider ServiceProvider = CreateSharedServiceProvider();

    public override IServiceScope CreateScope(DataGeneratorMetadata dataGeneratorMetadata)
    {
        return ServiceProvider.CreateScope();
    }

    public override object? Create(IServiceScope scope, Type type)
    {
        return scope.ServiceProvider.GetService(type);
    }

    private static IServiceProvider CreateSharedServiceProvider()
    {
        return new ServiceCollection()
            .AddSingleton<IOrderRepository, MockOrderRepository>()
            .AddSingleton<IDiscountCalculator, MockDiscountCalculator>()
            .AddSingleton<IShippingCalculator, MockShippingCalculator>()
            .AddSingleton<ILogger<OrderService>, MockLogger<OrderService>>()
            .AddTransient<OrderService>()
            .BuildServiceProvider();
    }
}

使用 TUnit 依賴注入

csharp
[MicrosoftDependencyInjectionDataSource]
public class DependencyInjectionTests(OrderService orderService)
{
    [Test]
    public async Task CreateOrder_使用TUnit依賴注入_應正確運作()
    {
        // Arrange - 依賴已經透過 TUnit DI 自動注入
        var items = new List<OrderItem>
        {
            new() { ProductId = "PROD001", ProductName = "測試商品", UnitPrice = 100m, Quantity = 2 }
        };

        // Act
        var order = await orderService.CreateOrderAsync("CUST001", CustomerLevel.VIP會員, items);

        // Assert
        await Assert.That(order).IsNotNull();
        await Assert.That(order.CustomerId).IsEqualTo("CUST001");
        await Assert.That(order.CustomerLevel).IsEqualTo(CustomerLevel.VIP會員);
    }

    [Test]
    public async Task TUnitDependencyInjection_驗證自動注入_服務應為正確類型()
    {
        await Assert.That(orderService).IsNotNull();
        await Assert.That(orderService.GetType().Name).IsEqualTo("OrderService");
    }
}

TUnit DI vs 手動依賴建立比較

特性TUnit DI手動依賴建立
設定複雜度一次設定,重複使用每個測試都需要手動建立
可維護性依賴變更只需修改一個地方需要修改所有使用的測試
一致性與產品程式碼的 DI 一致可能與實際應用程式不一致
測試可讀性專注於測試邏輯被依賴建立程式碼干擾
範圍管理自動管理服務範圍需要手動管理物件生命週期
錯誤風險框架保證依賴正確注入可能遺漏或錯誤建立某些依賴

執行控制與測試品質

  • [Retry(n)]:僅用於外部依賴造成的不穩定測試(網路、檔案鎖定),不用於邏輯錯誤
  • [Timeout(ms)]:為效能敏感測試設定合理上限,搭配 Stopwatch 驗證 SLA
  • [DisplayName]:支援 {0} 參數插值,讓測試報告更貼近業務語言

完整範例(Retry/Timeout/DisplayName)請參閱 references/execution-control.md


ASP.NET Core 整合測試

在 TUnit 中使用 WebApplicationFactory<Program> 進行 ASP.NET Core 整合測試,透過實作 IDisposable 管理生命週期。涵蓋 API 回應驗證、Content-Type 標頭檢查,以及效能基準與並行負載測試。

完整 WebApplicationFactory 整合與負載測試範例請參閱 references/aspnet-integration.md


TUnit + Testcontainers 基礎設施編排

使用 [Before(Assembly)] / [After(Assembly)] 在 Assembly 層級管理 PostgreSQL、Redis、Kafka 等多容器編排,搭配 NetworkBuilder 建立共用網路。容器僅啟動一次,大幅減少啟動時間與資源消耗,同時保持測試間的資料隔離。

完整多容器編排與全域共享範例請參閱 references/tunit-testcontainers.md


TUnit Engine Modes

Source Generation Mode(預設模式)

text
████████╗██╗   ██╗███╗   ██╗██╗████████╗
╚══██╔══╝██║   ██║████╗  ██║██║╚══██╔══╝
   ██║   ██║   ██║██╔██╗ ██║██║   ██║
   ██║   ██║   ██║██║╚██╗██║██║   ██║
   ██║   ╚██████╔╝██║ ╚████║██║   ██║
   ╚═╝    ╚═════╝ ╚═╝  ╚═══╝╚═╝   ╚═╝

   Engine Mode: SourceGenerated

特色與優勢:

  • 編譯時期產生:所有測試發現邏輯在編譯時產生,不需要執行時反射
  • 效能優異:比反射模式快數倍
  • 型別安全:編譯時期驗證測試配置和資料來源
  • AOT 相容:完全支援 Native AOT 編譯

Reflection Mode(反射模式)

bash
# 啟用反射模式
dotnet run -- --reflection

# 或設定環境變數
$env:TUNIT_EXECUTION_MODE = "reflection"
dotnet run

適用場景:

  • 動態測試發現
  • F# 和 VB.NET 專案(自動使用)
  • 某些依賴反射的測試模式

Native AOT 支援

xml
<PropertyGroup>
    <PublishAot>true</PublishAot>
</PropertyGroup>
bash
dotnet publish -c Release

常見問題與疑難排解

測試統計顯示異常問題

問題現象: 測試摘要: 總計: 0, 失敗: 0, 成功: 0

解決步驟:

  1. 確保專案檔設定正確:
xml
<PropertyGroup>
    <IsTestProject>true</IsTestProject>
</PropertyGroup>
  1. 確保 GlobalUsings.cs 正確:
csharp
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading.Tasks;
global using TUnit.Core;
global using TUnit.Assertions;
global using TUnit.Assertions.Extensions;
  1. 整合測試的特殊設定:
csharp
// 在 WebApi 專案的 Program.cs 最後加上
public partial class Program { }  // 讓整合測試可以存取
  1. 清理和重建:
bash
dotnet clean; dotnet build
dotnet test --verbosity normal

Source Generator 相關問題

問題:測試類別無法被發現

  • 解決:確保專案完全重建 (dotnet clean; dotnet build)

問題:編譯時出現奇怪錯誤

  • 解決:檢查是否有其他 Source Generator 套件,考慮更新到相容版本

診斷選項

ini
# .editorconfig
tunit.enable_verbose_diagnostics = true
xml
<PropertyGroup>
    <TUnitEnableVerboseDiagnostics>true</TUnitEnableVerboseDiagnostics>
</PropertyGroup>

實務建議

資料驅動測試的選擇策略

  • MethodDataSource:適合動態資料、複雜物件、外部檔案載入
  • ClassDataSource:適合共享資料、AutoFixture 整合、跨測試類別重用
  • Matrix Tests:適合組合測試,但要注意參數數量避免爆炸性增長

執行控制最佳實踐

  • Retry:只用於真正不穩定的外部依賴測試
  • Timeout:為效能敏感的測試設定合理限制
  • DisplayName:讓測試報告更符合業務語言

整合測試策略

  • 使用 WebApplicationFactory 進行完整的 Web API 測試
  • 運用 TUnit + Testcontainers 建立複雜多服務測試環境
  • 透過屬性注入系統管理複雜的依賴關係
  • 只測試實際存在的功能,避免測試不存在的端點

範本檔案

檔案名稱說明
data-source-examples.csMethodDataSource、ClassDataSource 範例
matrix-tests-examples.csMatrix Tests 組合測試範例
lifecycle-di-examples.cs生命週期管理與依賴注入範例
execution-control-examples.csRetry、Timeout、DisplayName 範例
aspnet-integration-tests.csASP.NET Core 整合測試範例
testcontainers-examples.csTestcontainers 基礎設施編排範例

輸出格式

  • 產生使用 MethodDataSource/ClassDataSource/Matrix Tests 的資料驅動測試類別(.cs 檔案)
  • 包含 MicrosoftDependencyInjectionDataSource 依賴注入設定
  • 包含 Retry/Timeout/DisplayName 執行控制範例
  • 產生 WebApplicationFactory 整合測試與 Testcontainers 多容器編排程式碼

參考資源

原始文章

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

TUnit 官方資源

進階功能文件

Testcontainers 相關資源

相關技能

  • dotnet-testing-advanced-tunit-fundamentals - TUnit 基礎(前置技能)
  • dotnet-testing-advanced-aspnet-integration-testing - ASP.NET Core 整合測試
  • dotnet-testing-advanced-testcontainers-database - Testcontainers 資料庫測試

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Dotnet Testing Advanced Tunit Advanced AI 技能有什么作用?

TUnit 進階應用完整指南。當需要使用 TUnit 進行資料驅動測試、依賴注入或整合測試時使用。涵蓋 MethodDataSource、ClassDataSource、Matrix Tests、Properties 過濾。包含 Retry/Timeout 控制、WebApplicationFactory 整合、Testcontainers 多服務編排。 Keywords: TUnit advanced, TUnit 進階, MethodDataSource, ClassDataSource, Matrix Tests, MatrixDataSource, MicrosoftDependencyInjectionDataSource, Property, Retry, Timeout, 資料驅動測試, 測試過濾, WebApplicationFactory TUnit, 多容器編排

为什么在 TypingMind 中使用 Dotnet Testing Advanced Tunit Advanced?

因为您只需安装一次,就能搭配任何模型使用。Dotnet Testing Advanced Tunit Advanced 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Dotnet Testing Advanced Tunit Advanced?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/kevintsengtw/dotnet-testing-agent-skills/tree/main/skills/dotnet-testing-advanced-tunit-advanced。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Dotnet Testing Advanced Tunit Advanced?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Dotnet Testing Advanced Tunit Advanced 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Dotnet Testing Advanced Tunit Advanced 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Dotnet Testing Advanced Tunit Advanced AI 技能免费吗?

是的。kevintsengtw 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇