跳到主内容
智客 ZICQ

技能库 智客分类:运维与云 testcontainers

Testcontainers

在.NET集成测试中使用Testcontainers来旋转像数据库和消息队列这样的真实依赖性的模式. 在写作需要真实数据库的集成测试时使用,使用RabbitMQ或Kafka等消息经纪人进行测试,或用多克容器隔离测试依赖性.

558 安装量

官方网址:skills.sh

技能介绍

先看中文介绍;官方 description 原文单独保留,不改写 SKILL.md。

做什么

在.NET集成测试中使用Testcontainers来旋转数据库和信件队列等真实依赖关系的规律

何时用

这个技能

代理如何加载

按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:Integration Testing with TestContainers、When to Use This Skill、Core Principles、Why TestContainers Over Mocks?、Problems with Mocking Infrastructure、Better: TestContainers with Real Database。

文件分析

文件分析:这是一份仅含 SKILL.md 的指令型技能,代理激活后整份正文进入上下文。

官方 description(原文)

Patterns for using Testcontainers in .NET integration tests to spin up real dependencies like databases and message queues. Use when writing integration tests that require real databases, testing with message brokers like RabbitMQ or Kafka, or isolating test dependencies with Docker containers.

Integration Testing with TestContainersWhen to Use This SkillCore PrinciplesWhy TestContainers Over Mocks?Problems with Mocking InfrastructureBetter: TestContainers with Real DatabaseRequired NuGet PackagesGetting StartedReference DocumentationBest Practices

来源分类:skills.sh agent-skill

SKILL.md 与 Agent 调用

官方规范 ↗
name
testcontainers
description
Patterns for using Testcontainers in .NET integration tests to spin up real dependencies like databases and message queues. Use when writing integration tests that require real databases, testing with message brokers like RabbitMQ or Kafka, or isolating test dependencies with Docker containers.
  1. 发现技能客户端向 Agent 提供名称与描述目录。
  2. 匹配与调用用户指定或任务匹配后,载入 SKILL.md 指令。
  3. 按需加载按步骤读取参考文档、使用脚本与素材。

具体调用语法与可用工具以目标 Agent 客户端为准。 查看调用机制说明 ↗

安装这个技能

Skills CLI ↗

先选择目标 Agent 和安装范围,保留技能包的附属文件,安装后检查客户端能否发现该技能。

交给 Agent 安装

复制安装指令给支持 Agent Skills 的代理,确认其中的目标目录与客户端匹配。

把 Agent Skill「testcontainers」安装到我的项目:SKILL.md 原文与官方 description 见 https://zicq.com/zh/skills/skl-667451f1c4d68918-%E6%B5%8B%E8%AF%95%E5%AE%B9%E5%99%A8.html
请存为 .cursor/skills/testcontainers/SKILL.md 或 .claude/skills/testcontainers/SKILL.md,frontmatter 的 name 与 description 保持原样,不要改写。

GitHub 完整包 ↗

终端安装 · Skills CLI

需要 Node.js 与 npx。先查看仓库技能列表,确认实际名称。

npx skills add 'https://github.com/wshaddix/dotnet-skills' --list

npx skills add 'https://github.com/wshaddix/dotnet-skills' --skill 'testcontainers'

CLI 会交互选择目标 Agent,默认安装到项目;用户级安装使用 -g。先通过查看命令核对仓库内容,再用 npx skills list 检查已安装技能。

阅读排版
--- name: testcontainers description: Patterns for using Testcontainers in .NET integration tests to spin up real dependencies like databases and message queues. Use when writing integration tests that require real databases, testing with message brokers like RabbitMQ or Kafka, or isolating test dependencies with Docker containers. --- # Integration Testing with TestContainers ## When to Use This Skill Use this skill when: - Writing integration tests that need real infrastructure (databases, caches, message queues) - Testing data access layers against actual databases - Verifying message queue integrations - Testing Redis caching behavior - Avoiding mocks for infrastructure components - Ensuring tests work against production-like environments - Testing database migrations and schema changes ## Core Principles 1. **Real Infrastructure Over Mocks** - Use actual databases/services in containers, not mocks 2. **Test Isolation** - Each test gets fresh containers or fresh data 3. **Automatic Cleanup** - TestContainers handles container lifecycle and cleanup 4. **Fast Startup** - Reuse containers across tests in the same class when appropriate 5. **CI/CD Compatible** - Works seamlessly in Docker-enabled CI environments 6. **Port Randomization** - Containers use random ports to avoid conflicts ## Why TestContainers Over Mocks? ### Problems with Mocking Infrastructure ```csharp // BAD: Mocking a database public class OrderRepositoryTests { private readonly Mock _mockDb = new(); [Fact] public async Task GetOrder_ReturnsOrder() { // This doesn't test real SQL behavior, constraints, or performance _mockDb.Setup(db => db.QueryAsync(It.IsAny())) .ReturnsAsync(new[] { new Order { Id = 1 } }); var repo = new OrderRepository(_mockDb.Object); var order = await repo.GetOrderAsync(1); Assert.NotNull(order); } } ``` Problems: - Doesn't test actual SQL queries - Misses database constraints, indexes, and performance - Can give false confidence - Doesn't catch SQL syntax errors or schema mismatches ### Better: TestContainers with Real Database ```csharp // GOOD: Testing against a real database public class OrderRepositoryTests : IAsyncLifetime { private readonly TestcontainersContainer _dbContainer; private IDbConnection _connection; public OrderRepositoryTests() { _dbContainer = new TestcontainersBuilder() .WithImage("mcr.microsoft.com/mssql/server:2022-latest") .WithEnvironment("ACCEPT_EULA", "Y") .WithEnvironment("SA_PASSWORD", "Your_password123") .WithPortBinding(1433, true) .Build(); } public async Task InitializeAsync() { await _dbContainer.StartAsync(); var port = _dbContainer.GetMappedPublicPort(1433); var connectionString = $"Server=localhost,{port};Database=TestDb;User Id=sa;Password=Your_password123;TrustServerCertificate=true"; _connection = new SqlConnection(connectionString); await _connection.OpenAsync(); // Run migrations await RunMigrationsAsync(_connection); } public async Task DisposeAsync() { await _connection.DisposeAsync(); await _dbContainer.DisposeAsync(); } [Fact] public async Task GetOrder_WithRealDatabase_ReturnsOrder() { // Arrange: Insert real test data await _connection.ExecuteAsync( "INSERT INTO Orders (Id, CustomerId, Total) VALUES (1, 'CUST1', 100.00)"); var repo = new OrderRepository(_connection); // Act: Execute against real database var order = await repo.GetOrderAsync(1); // Assert: Verify actual database behavior Assert.NotNull(order); Assert.Equal(1, order.Id); Assert.Equal("CUST1", order.CustomerId); Assert.Equal(100.00m, order.Total); } } ``` Benefits: - Tests real SQL queries and database behavior - Catches constraint violations, index issues, and performance problems - Verifies migrations work correctly - Gives true confidence in data access layer ## Required NuGet Packages ```xml ``` ## Getting Started The Testcontainers library provides a simple API for managing Docker containers in your tests. Each test can spin up the infrastructure it needs, and Testcontainers handles the lifecycle automatically. ## Reference Documentation For detailed patterns and examples, see the reference files: - **[Database Containers](./reference/database-containers.md)** - SQL Server, PostgreSQL, MySQL, and migration patterns - **[Message Broker Containers](./reference/message-broker-containers.md)** - RabbitMQ, Kafka, and Service Bus patterns - **[Advanced Patterns](./reference/advanced-patterns.md)** - Networks, volumes, wait strategies, cleanup, and performance optimization ## Best Practices 1. **Always Use IAsyncLifetime** - Proper async setup and teardown 2. **Wait for Port Availability** - Use `WaitStrategy` to ensure containers are ready 3. **Use Random Ports** - Let TestContainers assign ports automatically 4. **Clean Data Between Tests** - Either use fresh containers or truncate tables 5. **Reuse Containers When Possible** - Faster than creating new ones for each test 6. **Test Real Queries** - Don't just test mocks; verify actual SQL behavior 7. **Verify Constraints** - Test foreign keys, unique constraints, indexes 8. **Test Transactions** - Verify rollback and commit behavior 9. **Use Realistic Data** - Test with production-like data volumes 10. **Handle Cleanup** - Always dispose containers in `DisposeAsync`

相关技能

运维与云

Docker Essentials

用于容器管理,图像操作,调试的基本道克命令和工作流程.

运维与云

Find Skills

从开放的代理技能生态系统中发现并安装技能. 使用时:(1)用户问"我如何做X",X可能拥有现有技能,(2)用户说"为X找到技能"或"是否为X有技能",(3)用户问"你能否做X",X是专门能力,(4)用户想扩展代理能力,(5)用户想搜索工具,模板,或工作流程,(6)用户提到他们希望…

运维与云

Microsoft Foundry

构建,部署,评价,优化,微调,管理微软创始代理,模型,资源最终结束. 用法:铸造、azd ai代理、azd 提供/部署、托管代理脚手架/开发/运行/部署/拖放、即时代理创建、创建代理、更新代理、添加代理工具、援引代理、代理.yaml、评估代理、批量活化、连续活化、持续监测、代理C…

运维与云

Azure Deploy

执行已有.azure/部署计划.md和基础设施文件的ALREADY-PREPARED应用程序的Azure部署。 当用户向 CREATE 请求新应用程序时, 请不要使用此技能 。 这种技能运行了 azd上行, azd 部署, trarraform 应用, 和 az 部署命令带有内置…