SuperAPI AI 工具集

docker-testcontainers

测试与质量

查看项目

更新于 10-15 21:48

技能介绍

用途:该技能面向在自动化集成测试中使用 Docker 容器(Testcontainers),当用户提到 testcontainers、测试容器、集成测试、docker 测试、数据库测试(PostgreSQL/MySQL)、Java 或 Python Testcontainers、测试环境搭建时使用。

主要能力:Java 侧支持 @Testcontainers、@Container 注解,PostgreSQLContainer、GenericContainer、KafkaContainer 等模块,并可通过 @DynamicPropertySource 将容器连接信息注入 Spring 配置;Python 侧使用 testcontainers-python,配合 pytest fixture 提供 PostgresContainer、RedisContainer 等。容器使用随机端口,避免端口冲突,测试结束后由 Ryuk 自动清理。

使用方式:Java 依赖示例为 testImplementation 'org.testcontainers:testcontainers:1.20.6';定义容器如 @Container static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");通过 @DynamicPropertySource 注入 spring.datasource.url 等配置;编写 @Test 业务测试。Python 示例用 with PostgresContainer("postgres:16-alpine") as pg 并 yield pg.get_connection_url()。连接地址应使用 container.getMappedPort(5432) 而非硬编码端口。CI 中可用 GitHub Actions 的 docker:27-dind 服务(--privileged)运行测试,并可通过 withReuse(true) 与缓存加速。

适用场景:Java/Python 集成测试、Spring Boot 测试、CI 中自动启动与清理容器;跨 JVM 复用需配置 testcontainers.reuse.enable=true,非 Java 语言需使用对应语言库。

限制:不适用于手动测试或调试(用 docker run)、生产数据库测试(连接真实实例)、Mock 测试(用 Mockito/unittest.mock)、Docker 基础教学、性能压测(用 JMeter/K6)。切勿在生产代码中使用 Testcontainers,仅限测试范围。CI 中若禁用 Ryuk(TESTCONTAINERS_RYUK_DISABLED=true)需自行添加 @AfterAll 清理,并确认 Docker socket 已挂载。静态 @Container 字段在类内共享一个容器,实例字段则每个测试新建容器。

官方文档:https://docs.docker.com/testcontainers/、https://java.testcontainers.org/、https://testcontainers.com/cloud/。