testcontainers

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.

26 stars

Best use case

testcontainers is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

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.

Teams using testcontainers should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/testcontainers/SKILL.md --create-dirs "https://raw.githubusercontent.com/TerminalSkills/skills/main/skills/testcontainers/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/testcontainers/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How testcontainers Compares

Feature / AgenttestcontainersStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

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.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# 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

1. **Language** — JavaScript/TypeScript, Java, Python, Go, or .NET?
2. **Dependencies** — Which services need containerization? (databases, caches, queues)
3. **Test runner** — Jest, Vitest, JUnit, pytest?
4. **Docker** — Docker Desktop or CI Docker available?

### Setup (Node.js)

```bash
# setup-testcontainers.sh — Install Testcontainers for Node.js.
npm install --save-dev testcontainers
```

### PostgreSQL Integration Test

```typescript
// 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

```typescript
// 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

```typescript
// 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

```java
// 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

```yaml
# .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"
```

Related Skills

zustand

26
from TerminalSkills/skills

You are an expert in Zustand, the small, fast, and scalable state management library for React. You help developers manage global state without boilerplate using Zustand's hook-based stores, selectors for performance, middleware (persist, devtools, immer), computed values, and async actions — replacing Redux complexity with a simple, un-opinionated API in under 1KB.

zoho

26
from TerminalSkills/skills

Integrate and automate Zoho products. Use when a user asks to work with Zoho CRM, Zoho Books, Zoho Desk, Zoho Projects, Zoho Mail, or Zoho Creator, build custom integrations via Zoho APIs, automate workflows with Deluge scripting, sync data between Zoho apps and external systems, manage leads and deals, automate invoicing, build custom Zoho Creator apps, set up webhooks, or manage Zoho organization settings. Covers Zoho CRM, Books, Desk, Projects, Creator, and cross-product integrations.

zod

26
from TerminalSkills/skills

You are an expert in Zod, the TypeScript-first schema declaration and validation library. You help developers define schemas that validate data at runtime AND infer TypeScript types at compile time — eliminating the need to write types and validators separately. Used for API input validation, form validation, environment variables, config files, and any data boundary.

zipkin

26
from TerminalSkills/skills

Deploy and configure Zipkin for distributed tracing and request flow visualization. Use when a user needs to set up trace collection, instrument Java/Spring or other services with Zipkin, analyze service dependencies, or configure storage backends for trace data.

zig

26
from TerminalSkills/skills

Expert guidance for Zig, the systems programming language focused on performance, safety, and readability. Helps developers write high-performance code with compile-time evaluation, seamless C interop, no hidden control flow, and no garbage collector. Zig is used for game engines, operating systems, networking, and as a C/C++ replacement.

zed

26
from TerminalSkills/skills

Expert guidance for Zed, the high-performance code editor built in Rust with native collaboration, AI integration, and GPU-accelerated rendering. Helps developers configure Zed, create custom extensions, set up collaborative editing sessions, and integrate AI assistants for productive coding.

zeabur

26
from TerminalSkills/skills

Expert guidance for Zeabur, the cloud deployment platform that auto-detects frameworks, builds and deploys applications with zero configuration, and provides managed services like databases and message queues. Helps developers deploy full-stack applications with automatic scaling and one-click marketplace services.

zapier

26
from TerminalSkills/skills

Automate workflows between apps with Zapier. Use when a user asks to connect apps without code, automate repetitive tasks, sync data between services, or build no-code integrations between SaaS tools.

zabbix

26
from TerminalSkills/skills

Configure Zabbix for enterprise infrastructure monitoring with templates, triggers, discovery rules, and dashboards. Use when a user needs to set up Zabbix server, configure host monitoring, create custom templates, define trigger expressions, or automate host discovery and registration.

yup

26
from TerminalSkills/skills

Validate data with Yup schemas. Use when adding form validation, defining API request schemas, validating configuration, or building type-safe validation pipelines in JavaScript/TypeScript.

yt-dlp

26
from TerminalSkills/skills

Download video and audio from YouTube and other platforms with yt-dlp. Use when a user asks to download YouTube videos, extract audio from videos, download playlists, get subtitles, download specific formats or qualities, batch download, archive channels, extract metadata, embed thumbnails, download from social media platforms (Twitter, Instagram, TikTok), or build media ingestion pipelines. Covers format selection, audio extraction, playlists, subtitles, metadata, and automation.

youtube-transcription

26
from TerminalSkills/skills

Transcribe YouTube videos to text using OpenAI Whisper and yt-dlp. Use when the user wants to get a transcript from a YouTube video, generate subtitles, convert video speech to text, create SRT/VTT captions, or extract spoken content from YouTube URLs.