testcontainers
Testcontainersは、Dockerコンテナを使って実際の依存関係を持つ統合テストを簡単に行えるようにするSkillで、データベース連携テストやコンテナ化されたテスト環境構築を支援し、より信頼性の高いテストを実現するSkill。
📜 元の英語説明(参考)
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.
🇯🇵 日本人クリエイター向け解説
Testcontainersは、Dockerコンテナを使って実際の依存関係を持つ統合テストを簡単に行えるようにするSkillで、データベース連携テストやコンテナ化されたテスト環境構築を支援し、より信頼性の高いテストを実現するSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o testcontainers.zip https://jpskill.com/download/15472.zip && unzip -o testcontainers.zip && rm testcontainers.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/15472.zip -OutFile "$d\testcontainers.zip"; Expand-Archive "$d\testcontainers.zip" -DestinationPath $d -Force; ri "$d\testcontainers.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
testcontainers.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
testcontainersフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
Testcontainers
概要
あなたは、統合テストのために軽量で使い捨ての Docker コンテナを提供するライブラリである Testcontainers のエキスパートです。あなたは、テストスイートの一部として、実際のデータベース (PostgreSQL、MySQL、MongoDB)、メッセージブローカー (Kafka、RabbitMQ)、およびその他のサービスをスピンアップするのを支援します。あなたは、Node.js、Java、Python、Go、および .NET 用の Testcontainers API を理解しており、コンテナの起動時間を最適化する方法を知っています。
手順
初期評価
- Language — JavaScript/TypeScript、Java、Python、Go、または .NET ですか?
- Dependencies — どのサービスをコンテナ化する必要がありますか? (データベース、キャッシュ、キュー)
- Test runner — Jest、Vitest、JUnit、pytest ですか?
- Docker — Docker Desktop または CI Docker は利用可能ですか?
セットアップ (Node.js)
# setup-testcontainers.sh — Node.js 用の Testcontainers をインストールします。
npm install --save-dev testcontainers
PostgreSQL 統合テスト
// tests/user-repo.integration.test.ts — 実際の PostgreSQL コンテナを使用した統合テスト。
// Postgres をスピンアップし、移行を実行し、リポジトリをテストし、破棄します。
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 統合テスト
// tests/cache.integration.test.ts — 実際の Redis コンテナを使用した統合テスト。
// 実際の Redis コマンドを使用してキャッシュの動作をテストします。
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 モジュール
// tests/full-stack.integration.test.ts — Docker Compose を使用したマルチコンテナテスト。
// エンドツーエンドの統合テストのためにスタック全体をスピンアップします。
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 — JUnit 5 と PostgreSQL を使用した Testcontainers。
// 自動ライフサイクル管理のために @Container アノテーションを使用します。
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 📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Testcontainers
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"