testcontainers
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "testcontainers":https://skillpi.com/zh/skills/deepskill-e931c8eb5d4064e5c084b1f473753c18b98d1da7abc3c3eb94bd360331dc6022。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
用于在集成测试中以 Testcontainers 管理的 Docker 容器运行真实依赖项的工具。当用户提到 “testcontainers”、使用 Docker 进行集成测试、数据库集成测试、容器化测试或使用真实数据库进行测试时适用。对于不使用容器的 API 模拟,请参见 mockoon 或 wiremock。
介绍来源: third_party · TerminalSkills · 1.0.0 参考来源
SkillPi 解读
- 能完成的任务
- 翻译待完成,请参阅来源文档。
- 软件、账号及付费要求
- 贝什
- 实测状态
- 未测试
文件浏览
Frontmatter
name: testcontainers
description: When the user wants to run integration tests with real dependencies using Docker containers managed by Testcontainers. Also use when the user mentions "testcontainers," "integration testing with Docker," "database integration tests," "containerized tests," or "test with real database." For API mocking without containers, see mockoon or wiremock.
metadata:
author: terminal-skills
version: "1.0.0"
category: development
tags:
- integration-testing
- docker
- databases
- containersTestcontainers
Overview
You are an expert in Testcontainers, the library that provides lightweight, throwaway Docker containers for integration testing. You help users spin up real databases (PostgreSQL, MySQL, MongoDB), message brokers (Kafka, RabbitMQ), and other services as part of their test suite. You understand the Testcontainers API for Node.js, Java, Python, Go, and .NET, and know how to optimize container startup times.
Instructions
Initial Assessment
- Language — JavaScript/TypeScript, Java, Python, Go, or .NET?
- Dependencies — Which services need containerization? (databases, caches, queues)
- Test runner — Jest, Vitest, JUnit, pytest?
- Docker — Docker Desktop or CI Docker available?
Setup (Node.js)
# setup-testcontainers.sh — Install Testcontainers for Node.js.
npm install --save-dev testcontainers
PostgreSQL Integration Test
// tests/user-repo.integration.test.ts — Integration test with a real PostgreSQL container.
// Spins up Postgres, runs migrations, tests the repository, tears down.
import { PostgreSqlContainer, StartedPostgreSqlContainer } from '@testcontainers/postgresql';
import { Pool } from 'pg';
import { UserRepository } from '../src/repositories/userRepo';
import { runMigrations } from '../src/db/migrate';
describe('UserRepository', () => {
let container: StartedPostgreSqlContainer;
let pool: Pool;
let repo: UserRepository;
beforeAll(async () => {
container = await new PostgreSqlContainer('postgres:16')
.withDatabase('testdb')
.withUsername('test')
.withPassword('test')
.start();
pool = new Pool({ connectionString: container.getConnectionUri() });
await runMigrations(pool);
repo = new UserRepository(pool);
}, 60000);
afterAll(async () => {
await pool.end();
await container.stop();
});
afterEach(async () => {
await pool.query('DELETE FROM users');
});
it('should create and retrieve a user', async () => {
const created = await repo.create({ name: 'Jane', email: 'jane@test.com' });
expect(created.id).toBeDefined();
const found = await repo.findById(created.id);
expect(found).toMatchObject({ name: 'Jane', email: 'jane@test.com' });
});
it('should return null for non-existent user', async () => {
const found = await repo.findById(99999);
expect(found).toBeNull();
});
});
Redis Integration Test
// tests/cache.integration.test.ts — Integration test with a real Redis container.
// Tests caching behavior with actual Redis commands.
import { GenericContainer, StartedTestContainer } from 'testcontainers';
import { createClient, RedisClientType } from 'redis';
import { CacheService } from '../src/services/cache';
describe('CacheService', () => {
let container: StartedTestContainer;
let redis: RedisClientType;
let cache: CacheService;
beforeAll(async () => {
container = await new GenericContainer('redis:7-alpine')
.withExposedPorts(6379)
.start();
redis = createClient({
url: `redis://${container.getHost()}:${container.getMappedPort(6379)}`,
});
await redis.connect();
cache = new CacheService(redis);
}, 30000);
afterAll(async () => {
await redis.quit();
await container.stop();
});
it('should cache and retrieve values', async () => {
await cache.set('key1', { data: 'hello' }, 60);
const result = await cache.get('key1');
expect(result).toEqual({ data: 'hello' });
});
it('should return null for expired keys', async () => {
await cache.set('temp', 'value', 1);
await new Promise((r) => setTimeout(r, 1500));
const result = await cache.get('temp');
expect(result).toBeNull();
});
});
Docker Compose Module
// tests/full-stack.integration.test.ts — Multi-container test using Docker Compose.
// Spins up an entire stack for end-to-end integration testing.
import { DockerComposeEnvironment, StartedDockerComposeEnvironment } from 'testcontainers';
import { resolve } from 'path';
describe('Full Stack Integration', () => {
let environment: StartedDockerComposeEnvironment;
beforeAll(async () => {
environment = await new DockerComposeEnvironment(
resolve(__dirname, '..'),
'docker-compose.test.yml'
)
.withWaitStrategy('api-1', { type: 'HTTP', path: '/health', port: 3000 })
.up();
}, 120000);
afterAll(async () => {
await environment.down();
});
it('should process orders end-to-end', async () => {
const apiContainer = environment.getContainer('api-1');
const apiPort = apiContainer.getMappedPort(3000);
const baseUrl = `http://localhost:${apiPort}`;
const res = await fetch(`${baseUrl}/api/orders`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ item: 'widget', quantity: 3 }),
});
expect(res.status).toBe(201);
const order = await res.json();
expect(order.id).toBeDefined();
});
});
Java with JUnit 5
// src/test/java/UserRepoTest.java — Testcontainers with JUnit 5 and PostgreSQL.
// Uses @Container annotation for automatic lifecycle management.
import org.junit.jupiter.api.*;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.sql.*;
@Testcontainers
class UserRepoTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16")
.withDatabaseName("testdb")
.withUsername("test")
.withPassword("test");
private Connection conn;
@BeforeEach
void setUp() throws SQLException {
conn = DriverManager.getConnection(
postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()
);
conn.createStatement().execute(
"CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name TEXT, email TEXT)"
);
}
@Test
void shouldInsertAndRetrieveUser() throws SQLException {
conn.createStatement().execute("INSERT INTO users (name, email) VALUES ('Jane', 'jane@test.com')");
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM users WHERE name = 'Jane'");
Assertions.assertTrue(rs.next());
Assertions.assertEquals("jane@test.com", rs.getString("email"));
}
}
CI Integration
# .github/workflows/integration.yml — Run Testcontainers tests in GitHub Actions.
# Docker is available by default on ubuntu-latest runners.
name: Integration Tests
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npm run test:integration
env:
TESTCONTAINERS_RYUK_DISABLED: "true"当前收录版本
1.0.0
安全与评测信息
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- 高价值/高频刚需。Testcontainers 是开发者在集成测试中广泛使用的工具,直接解决真实依赖项测试的核心痛点,显著提升测试效率和可靠性。
亮点
- 触发词精准完整,覆盖多种变体,边界清晰。
亮点
- Phase/步骤清晰,有出口条件,含端到端示例,frontmatter完整,单文件≤500行。
亮点
- 工具来源明确,参数正确,覆盖主要异常,不可逆操作有确认机制。
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
-
安装或获取外部依赖
使用官方来源并锁定版本,在隔离环境检查安装脚本。当前文档检查不覆盖后续下载的代码。
主文档提及 · 第 34 行
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
贝什
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。