跳到主内容
智客 ZICQ

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

Docker Testcontainers

Guidance for Testcontainers — running Docker containers in automated integration tests. Covers Java (@Testcontainers, @Container, PostgreSQL/Redis/Kafka/Elasticsearch), Python (testcontainers-python with pytest), container lifecycle management (singleton, reuse), CI/CD integration (Docker-in-Docker, Ryuk), Testcontainer best practices, and database migration testing. Use when the user asks about testcontainers, integration testing with Docker, database testing, Java testcontainers, Python testcontainers, or needs to test with real Docker services. 使用场景:testcontainers、集成测试、docker 测试、数据库测试、Java Testcontainers、Python Testcontainers.

80 安装量

官方网址:skills.sh

技能介绍

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

做什么

Testcontainers指南——在自动化集成测试中运行多克容器. 覆盖 Java (@ Testcontainers, @ Container, PostgreSQL/Redis/Kafka/ Elasticsearch), Python (testcontainers-python with pytest), 容器生命周期管理( singleton,再利用), CI/CD集成(Docker-in-Docker, Ryuk), Testcontainer 最佳做法和数据库迁移测试

何时用

** 用户提到时总是使用这种技能:**

代理如何加载

按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:Docker Testcontainers — 集成测试容器、When to Use、Java — Testcontainers、PostgreSQL Example、Redis Example、Kafka Example。 其中含规范建议的小节:分步指令、输入输出示例。

文件分析

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

Docker Testcontainers — 集成测试容器When to UseJava — TestcontainersPostgreSQL ExampleRedis ExampleKafka ExamplePython — testcontainers-pythonContainer LifecycleCI/CD ConfigurationGitHub Actions — DinD (Docker-in-Docker)Workflow — 推荐集成流程Gotchas — Common Pitfalls

· 许可:Apache-2.0

来源分类:skills.sh agent-skill

SKILL.md 与 Agent 调用

官方规范 ↗
name
docker-testcontainers
description
Guidance for Testcontainers — running Docker containers in automated integration tests. Covers Java (@Testcontainers, @Container, PostgreSQL/Redis/Kafka/Elasticsearch), Python (testcontainers-python with pytest), container lifecycle management (singleton, reuse), CI/CD integration (Docker-in-Docker, Ryuk), Testcontainer best practices, and database migration testing. Use when the user asks about testcontainers, integration testing with Docker, database testing, Java testcontainers, Python testcontainers, or needs to test with real Docker services. 使用场景:testcontainers、集成测试、docker 测试、数据库测试、Java Testcontainers、Python Testcontainers.
许可
Apache-2.0
  1. 发现技能客户端向 Agent 提供名称与描述目录。
  2. 匹配与调用用户指定或任务匹配后,载入 SKILL.md 指令。
  3. 按需加载按步骤读取参考文档、使用脚本与素材。

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

安装这个技能

Skills CLI ↗

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

交给 Agent 安装

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

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

GitHub 完整包 ↗

终端安装 · Skills CLI

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

npx skills add 'https://github.com/full-stack-skills/docker-skills' --list

npx skills add 'https://github.com/full-stack-skills/docker-skills' --skill 'docker-testcontainers'

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

阅读排版

name: docker-testcontainers description: Guidance for Testcontainers — running Docker containers in automated integration tests. Covers Java (@Testcontainers, @Container, PostgreSQL/Redis/Kafka/Elasticsearch), Python (testcontainers-python with pytest), container lifecycle management (singleton, reuse), CI/CD integration (Docker-in-Docker, Ryuk), Testcontainer best practices, and database migration testing. Use when the user asks about testcontainers, integration testing with Docker, database testing, Java testcontainers, Python testcontainers, or needs to test with real Docker services. 使用场景:testcontainers、集成测试、docker 测试、数据库测试、Java Testcontainers、Python Testcontainers. license: Apache-2.0

Docker Testcontainers — 集成测试容器

Guidance for running Docker containers in automated tests with Testcontainers.

When to Use

ALWAYS use this skill when the user mentions:

  • "testcontainers", "Testcontainer", "测试容器"
  • "集成测试", "docker 测试"
  • "数据库测试", "PostgreSQL test", "MySQL test"
  • "Java Testcontainers", "Python Testcontainers"
  • "测试环境搭建"

Java — Testcontainers

PostgreSQL Example

@Testcontainers
@SpringBootTest
class OrderRepositoryTest {

    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
            .withDatabaseName("testdb")
            .withUsername("test")
            .withPassword("test");

    @DynamicPropertySource
    static void configure(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }

    @Test
    void shouldSaveAndFindOrder() {
        Order saved = repository.save(new Order(...));
        assertThat(repository.findById(saved.getId())).isPresent();
    }
}

Redis Example

@Container
static GenericContainer<?> redis = new GenericContainer<>("redis:7-alpine")
        .withExposedPorts(6379);

// Get connection string
String redisUrl = "redis://" + redis.getHost() + ":" + redis.getMappedPort(6379);

Kafka Example

@Container
static KafkaContainer kafka = new KafkaContainer(
        DockerImageName.parse("confluentinc/cp-kafka:7.6.0"));

String bootstrapServers = kafka.getBootstrapServers();

Python — testcontainers-python

import pytest
from testcontainers.postgres import PostgresContainer
from testcontainers.redis import RedisContainer

@pytest.fixture(scope="module")
def postgres():
    with PostgresContainer("postgres:16-alpine") as pg:
        yield pg.get_connection_url()

def test_database_connection(postgres):
    import psycopg2
    conn = psycopg2.connect(postgres)
    assert conn.status == psycopg2.STATUS_READY

Container Lifecycle

// Singleton: one container for all tests
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");

// Per-test: new container for each test
@Test
void test() {
    try (var redis = new GenericContainer<>("redis:7")) {
        redis.start();
        // test...
    } // auto-closed by try-with-resources
}

CI/CD Configuration

# GitHub Actions — DinD (Docker-in-Docker)
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      docker:
        image: docker:27-dind
        options: --privileged
    steps:
      - uses: actions/checkout@v4
      - run: ./gradlew test

Workflow — 推荐集成流程

Step 1: 添加依赖: testImplementation 'org.testcontainers:testcontainers:1.20.6' Step 2: 定义容器: @Container static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine") Step 3: 注入配置: @DynamicPropertySource 将容器连接信息注入 Spring 配置 Step 4: 编写测试: @Test void shouldSaveAndFind() 正常业务测试 Step 5: CI 加速: 启用 withReuse(true) + GHA cache

Gotchas — Common Pitfalls

  • CI slow startup: Container images need to be pulled in CI. → Recovery: Pre-warm by adding docker pull postgres:16-alpine before test step; enable withReuse(true) in .testcontainers.properties.
  • Port conflicts in CI: Testcontainers picks random ports — no conflicts. But hardcoded ports in tests will fail. → Recovery: Always use container.getMappedPort(5432) instead of hardcoding port numbers.
  • Resource cleanup: Ryuk auto-removes containers. In CI, ensure DinD or socket access. → Recovery: If TESTCONTAINERS_RYUK_DISABLED=true, add @AfterAll cleanup; check Docker socket is mounted in CI.
  • Static vs instance containers: Static @Container fields share ONE container across the class. Instance fields create per-test containers. → Recovery: Use static for databases (shared state OK); use instance for isolation-critical tests; check @TestInstance(TestInstance.Lifecycle.PER_CLASS) for JUnit 5.

Boundary — 能力边界(适用与不适用场景)

| 分类 | 场景 | 说明 | |------|------|------| | ✅ 能做 | Java/Python 集成测试 | PostgreSQL/MySQL/Redis/Kafka 等容器化数据库测试 | | ✅ 能做 | Spring Boot 测试 | @Testcontainers + @DynamicPropertySource 自动注入 | | ✅ 能做 | CI 集成 | GitHub Actions/Jenkins 中自动启动/清理 | | ⚠️ 需条件 | 跨 JVM 复用 | 需配置 testcontainers.reuse.enable=true | | ⚠️ 需条件 | 非 Java 语言测试 | 使用各语言对应 Testcontainers 库 | | ❌ 超范围 | 手动测试/调试 | 使用 docker-run | | ❌ 超范围 | 生产数据库测试 | 连接生产实例而非容器 | | ❌ 超范围 | 性能/压测 | 专用工具(JMeter/K6) |

When NOT to Use This Skill

| ❌ Skip | ✅ Use Instead | |---------|---------------| | Manual testing | docker-run | | Production database testing | docker-storage + real instance | | Mock testing | Use Mockito/unittest.mock | | Docker basics | docker-basics |

Security & Stability

  • Testcontainers use random ports — no port conflicts with running services.
  • Containers are automatically cleaned up by Ryuk after test completion.
  • Never use Testcontainers in production code — test scope only.
  • Use withReuse(true) for local development to speed up tests (container survives between runs).

📚 官方文档参考

| 文档 | 地址 | |------|------| | Testcontainers 概述 | https://docs.docker.com/testcontainers/ | | Testcontainers for Java | https://java.testcontainers.org/ | | Testcontainers Cloud | https://testcontainers.com/cloud/ | | Spring Boot 集成 | https://java.testcontainers.org/modules/spring-boot/ | | CI 配置 | https://java.testcontainers.org/supported_docker_environment/continuous_integration/ |

🧭 Docker Skills Journey

📍 You are here: docker-testcontainers — 测试容器

← Prev: docker-troubleshooting — Problem debugging → Next: docker-ai-ml — AI/ML workloads

FAQ

Q1: 如何快速上手此技能? A: 参考上方的快速开始章节,按步骤操作即可。

Q2: 遇到版本不兼容问题怎么办? A: 检查依赖版本,使用 lock 文件锁定,参考常见陷阱章节。

Q3: 如何在生产环境使用? A: 参考最佳实践章节,确保配置正确,做好监控和日志。

Q4: 性能如何优化? A: 参考性能优化相关文档,使用缓存、索引等手段。

Q5: 如何贡献或反馈问题? A: 在 GitHub 仓库提交 Issue 或 Pull Request。

Q6: 是否支持中文? A: 支持中文文档和中文注释,详见国内适配章节。

相关技能

运维与云

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 部署命令带有内置…