Installation
Install as Agent Plugin
Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install java-testcontainers@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin java-testcontainers v1.0.0 follows the Agent Plugins spec.
Install with the gh extension
gh skills-hub install java-testcontainers Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/java-testcontainers/ Extract the ZIP to .github/skills/ in your repo. The folder name must match java-testcontainers for Copilot to auto-discover it.
Skill Files (4)
SKILL.md 5.9 KB
---
name: java-testcontainers
description: 'Write reliable integration tests in plain Java with Testcontainers 2.x: JUnit Jupiter lifecycle, singleton containers, reuse, generic containers, wait strategies, networks, init scripts, Docker Compose, CI and Docker/Podman setup. Use when adding or fixing Testcontainers tests, or migrating from 1.x. Framework-neutral.'
---
# Java Testcontainers (2.x)
Run real dependencies (databases, brokers, caches) in Docker for integration tests. This skill is framework-neutral. If the project uses Spring Boot and the `spring-boot-testing` skill is installed, use it for `@ServiceConnection`, `@DynamicPropertySource` and test slices; for Quarkus, rely on Dev Services (Quarkus skills/docs), not hand-wired containers.
## Workflow
1. Detect the existing version (`pom.xml` / `build.gradle`) and test framework (JUnit Jupiter). Testcontainers 2.x has no JUnit 4 support.
2. Pick the smallest container that matches production (same DB engine and major version; never H2 as a stand-in for behavior you care about).
3. Choose a lifecycle (table below), configure waiting, wire connection details into the code under test.
4. Run locally and in CI; check Docker availability and speed.
## Testcontainers 2.x essentials
- Artifacts are all prefixed `testcontainers-`: `org.testcontainers:testcontainers-junit-jupiter`, `testcontainers-postgresql`, `testcontainers-mysql`, `testcontainers-kafka`, etc. (1.x: `junit-jupiter`, `postgresql`). Core stays `org.testcontainers:testcontainers`.
- Module container classes moved to per-module packages, e.g. `org.testcontainers.postgresql.PostgreSQLContainer` (1.x: `org.testcontainers.containers.PostgreSQLContainer`). Core classes (`GenericContainer`, `Network`, `wait.strategy.*`) remain under `org.testcontainers.containers`.
- Module container classes are no longer generic: `PostgreSQLContainer`, not `PostgreSQLContainer<?>`.
- Use a BOM to keep versions aligned: `org.testcontainers:testcontainers-bom:2.0.5` (verify the current release on Maven Central).
- Docker Compose: use `ComposeContainer` (Compose v2); `DockerComposeContainer` is still present in 2.0.5 (older API); prefer `ComposeContainer`.
```xml
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>2.0.5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.14</version>
<scope>test</scope>
</dependency>
</dependencies>
```
Gradle: `testImplementation platform("org.testcontainers:testcontainers-bom:2.0.5")`, then the same Testcontainers artifacts without versions, plus `testRuntimeOnly "org.postgresql:postgresql:42.7.14"`. The Testcontainers module does not bundle the JDBC driver; skip the explicit driver when the project already depends on one (e.g. via Spring Boot's BOM).
## Minimal test
```java
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.postgresql.PostgreSQLContainer;
@Testcontainers
class CustomerStoreIT {
@Container
static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:17-alpine");
@Test
void connects() throws Exception {
try (var c = java.sql.DriverManager.getConnection(
POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) {
org.junit.jupiter.api.Assertions.assertTrue(c.isValid(2));
}
}
}
```
Always pin the image tag (never `latest`); match the production major version.
## Lifecycle decision
| Need | Pattern |
| --- | --- |
| One container per test class | `static @Container` field |
| Fresh container per test method (slow, strong isolation) | non-static `@Container` field |
| One container for the whole test run (fastest) | singleton holder, see `references/lifecycle-and-reuse.md` |
| Keep containers between local runs | `withReuse(true)` + opt-in property, local only |
Prefer sharing a container and isolating **data** (truncate/rollback, unique schema or DB per test) over restarting containers.
## Checklist
- [ ] Image tag pinned and matches production.
- [ ] Wait strategy meaningful (module defaults are usually fine; custom for `GenericContainer`).
- [ ] No fixed host ports; use `getMappedPort`/`getHost`.
- [ ] Containers shared across classes where possible (singleton).
- [ ] Integration tests named `*IT` and run by failsafe (Maven) or a separate Gradle test task, so unit tests stay fast.
- [ ] No secrets or real credentials in test containers.
- [ ] CI runner has Docker; log output is captured on failure.
## References
- `references/lifecycle-and-reuse.md`: per-class/per-method, singleton pattern, reuse, parallel runs, data isolation.
- `references/containers-and-waiting.md`: modules vs `GenericContainer`, wait strategies, env/config, init scripts, copy files, networks, multi-container setups, Docker Compose.
- `references/environment-ci-troubleshooting.md`: Docker/Podman/Colima setup, CI, private registries, performance, common errors, 1.x to 2.x migration table.
Official docs: <https://java.testcontainers.org/>
Upgrading to 2.x: no dedicated migration page was found on java.testcontainers.org; read the 2.0.0 release notes <https://github.com/testcontainers/testcontainers-java/releases/tag/2.0.0> and all releases <https://github.com/testcontainers/testcontainers-java/releases> for the target version, and prefer them over this skill when they conflict.
references/
containers-and-waiting.md 4.3 KB
# Containers, waiting, networks, Compose
## Modules vs GenericContainer
Prefer a dedicated module (`testcontainers-postgresql`, `-mysql`, `-mariadb`, `-kafka`, `-mongodb`, `-localstack`, ...) when one exists: it supplies the right wait strategy, credentials, and typed getters. Fall back to `GenericContainer` for anything else.
```java
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import java.time.Duration;
GenericContainer<?> app = new GenericContainer<>("my-registry/my-service:1.4.2")
.withExposedPorts(8080)
.withEnv("MODE", "test")
.waitingFor(Wait.forHttp("/health").forStatusCode(200))
.withStartupTimeout(Duration.ofMinutes(2));
```
## Wait strategies
Set via `waitingFor(...)`. Pick the signal that means "actually ready", not "process started".
| Strategy | Use |
| --- | --- |
| `Wait.forListeningPorts()` | Port open (may be before the app is ready) |
| `Wait.forHttp(path).forStatusCode(200)` | HTTP health endpoints |
| `Wait.forLogMessage(regex, times)` | Ready line in logs (regex must match the whole line, e.g. `.*ready.*\\n`) |
| `Wait.forHealthcheck()` | Image defines `HEALTHCHECK` |
| `Wait.forSuccessfulCommand("cmd")` | Probe via exec inside the container |
| `new WaitAllStrategy().withStrategy(a).withStrategy(b)` | Combine strategies (`org.testcontainers.containers.wait.strategy.WaitAllStrategy`) |
Raise `withStartupTimeout` on slow CI instead of adding sleeps. Never use `Thread.sleep`; poll with Awaitility for asynchronous outcomes in tests.
## Configuration and files
- `withEnv`, `withCommand`, `withLabel`, `withTmpFs(Map.of("/var/lib/postgresql/data", "rw"))` (RAM-backed data dir speeds DB tests).
- Classpath resources: `withCopyFileToContainer(MountableFile.forClasspathResource("conf.yml"), "/etc/app/conf.yml")` (preferred over bind mounts: works with remote Docker).
- Bind mounts (`withFileSystemBind`) break on remote daemons and some rootless setups; avoid.
## Init scripts
Database modules: `withInitScript("db/init.sql")` (classpath) runs once after start. Alternatively copy scripts into `/docker-entrypoint-initdb.d/` (official Postgres/MySQL images). For schema evolution, run your real migration tool (Flyway/Liquibase) against the container rather than duplicating DDL in init scripts.
## Networks and multi-container setups
Containers reach each other by network alias, not by mapped port.
```java
import org.testcontainers.containers.Network;
Network net = Network.newNetwork(); // cleaned up by Ryuk
var db = new PostgreSQLContainer("postgres:17-alpine")
.withNetwork(net).withNetworkAliases("db");
var app = new GenericContainer<>("my-registry/my-service:1.4.2")
.withNetwork(net)
.withEnv("DB_URL", "jdbc:postgresql://db:5432/test")
.dependsOn(db)
.withExposedPorts(8080);
```
Inside the network use the container-internal port (5432); from the test JVM use `getMappedPort`.
## Docker Compose module
For stacks already described in a compose file, use `ComposeContainer` (requires the Docker Compose v2 CLI; class `org.testcontainers.containers.ComposeContainer`, in the core artifact).
```java
import org.testcontainers.containers.ComposeContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import java.io.File;
static ComposeContainer env = new ComposeContainer(new File("src/test/resources/compose-test.yml"))
.withExposedService("api", 8080, Wait.forHttp("/health").forStatusCode(200))
.withExposedService("db", 5432);
env.start(); // endpoints are only available after start
try {
String host = env.getServiceHost("api", 8080);
Integer port = env.getServicePort("api", 8080);
// run the test against host:port
} finally {
env.stop();
}
```
Do not publish fixed host ports in the compose file used for tests. Prefer individual containers for one or two services (faster, typed); use Compose to reuse a multi-service definition.
## Useful extras
- `container.followOutput(new Slf4jLogConsumer(log))` to stream logs; `getLogs()` on failure.
- `withCreateContainerCmdModifier(cmd -> cmd.getHostConfig().withMemory(512L * 1024 * 1024))` to cap resources.
- `DockerImageName.parse("mirror/postgres:17").asCompatibleSubstituteFor("postgres")` for mirrored or custom images with a module.
environment-ci-troubleshooting.md 4.7 KB
# Environment, CI, troubleshooting, migration
## Docker availability
Testcontainers needs a Docker-API-compatible daemon. Check with `docker info`.
- Docker Desktop, Rancher Desktop, Colima, OrbStack, and Podman (Docker-compatible socket) work. When the socket is non-standard, set `DOCKER_HOST` (e.g. `unix:///run/user/1000/podman/podman.sock`); with rootless Podman, `TESTCONTAINERS_RYUK_DISABLED=true` may be needed if the Ryuk sidecar cannot mount the socket (then clean up containers yourself).
- Settings can live in `~/.testcontainers.properties` (`docker.host=...`) or `TESTCONTAINERS_*` environment variables.
- Colima on macOS: `DOCKER_HOST=unix://$HOME/.colima/default/docker.sock` and `TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE=/var/run/docker.sock`.
- Without Docker, tests fail with "Could not find a valid Docker environment". Fix the environment, or gate optional local runs with `@Testcontainers(disabledWithoutDocker = true)`.
## CI
- GitHub Actions `ubuntu-*` runners ship Docker; no setup needed. Self-hosted runners must expose the socket to the job user.
- Docker-in-Docker CI (GitLab, containerized Jenkins agents): mount the host socket or use a DinD service and set `DOCKER_HOST`; set `TESTCONTAINERS_HOST_OVERRIDE` if the daemon host is not localhost.
- Cache images between runs and avoid Docker Hub rate limits with a registry mirror (`hub.image.name.prefix` in properties or `TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX`).
- Private registries: `docker login` (credential helpers in `~/.docker/config.json` are honored).
- Do not enable container reuse in CI.
- Print container logs on failure and keep timeouts generous (2 minutes for heavy images).
- Separate unit and integration phases (`maven-failsafe-plugin` with `*IT`, or a Gradle `integrationTest` task).
## Performance checklist
1. Singleton containers across classes (see `lifecycle-and-reuse.md`).
2. Small images (`-alpine`, slim) pinned by tag; pre-pull in CI.
3. `withTmpFs` for database data dirs.
4. Truncate/rollback instead of restarting.
5. Start independent containers in parallel (`Startables.deepStart(a, b, c).join()`, `org.testcontainers.lifecycle.Startables`).
6. Avoid heavyweight services if a lighter equivalent preserves the behavior under test.
## Common errors
| Symptom | Likely cause / fix |
| --- | --- |
| `Could not find a valid Docker environment` | Daemon down or wrong socket; set `DOCKER_HOST`. |
| Container startup timeout | Wrong wait strategy, image crash (read `getLogs()`), low resources; raise timeout. |
| Connection refused right after start | Port open but app not ready; use HTTP/log/healthcheck wait. |
| Works for first class, fails for next | `@Container` on a singleton stopped after first class; remove the annotation. |
| Container cannot reach another | Mapped port used inside a network; use alias + internal port. |
| `ClassNotFoundException: ...containers.PostgreSQLContainer` | 2.x package move, see below. |
| Ryuk errors | Rootless/Podman socket mount; see Docker availability. |
| Surefire `The exit has elapsed 30 seconds after System.exit(0)` / `going to kill self fork JVM` | A JVM shutdown hook hangs after the tests (not a Testcontainers-specific message). Not reproduced with Testcontainers 2.0.5 + Surefire 3.5.5/3.5.6 + Docker Desktop 29.8 on JDK 21/25/27, with static `@Container`, `@ServiceConnection` and a Spring-managed container bean (all exit in a second), so Docker Desktop, Ryuk and Testcontainers 2.x are not the cause by themselves. Diagnose: run `jstack <fork pid>` (or `jcmd Thread.print`) during the 30 s and read which hook thread is blocked (typically an application or Spring context hook closing a pool or client against a container that is already gone, or a user-registered hook); close such resources before the container stops, or set `-Dsurefire.exitTimeout=<seconds>` lower to fail fast. |
## 1.x to 2.x migration
| 1.x | 2.x |
| --- | --- |
| `org.testcontainers:junit-jupiter` | `org.testcontainers:testcontainers-junit-jupiter` |
| `org.testcontainers:postgresql` (and other modules) | `org.testcontainers:testcontainers-postgresql` (same prefix rule) |
| `org.testcontainers.containers.PostgreSQLContainer<?>` | `org.testcontainers.postgresql.PostgreSQLContainer` (non-generic) |
| JUnit 4 `@Rule`/`@ClassRule` | Removed; migrate tests to JUnit Jupiter |
| `DockerComposeContainer` | `ComposeContainer` (Compose v2) |
| Per-module versions | `testcontainers-bom` |
Steps: import the BOM, rename artifacts, fix imports module by module (the compiler flags each moved class), remove `<?>` from module container types, convert JUnit 4 tests. Check the release notes for the modules you use; each module's package follows `org.testcontainers.<module>`.
Docs: <https://java.testcontainers.org/>; releases: <https://github.com/testcontainers/testcontainers-java/releases>
lifecycle-and-reuse.md 2.9 KB
# Lifecycle, singleton and reuse
## JUnit Jupiter extension
`@Testcontainers` on the class activates the extension; `@Container` fields are started/stopped by it.
- `static` field: started once before all tests of the class, stopped after.
- instance field: started/stopped around each test method.
- The extension does not start containers declared without `@Container`; call `start()` yourself.
`@Testcontainers(disabledWithoutDocker = true)` skips tests (instead of failing) when Docker is missing. Use it for optional local runs; in CI prefer failing loudly.
## Singleton container pattern (whole run)
Starting a container per class dominates test time. Share one instance across classes with a holder that starts in a static initializer. Ryuk (the cleanup sidecar) stops it when the JVM exits, so no explicit stop is needed.
```java
import org.testcontainers.postgresql.PostgreSQLContainer;
public final class SharedPostgres {
public static final PostgreSQLContainer INSTANCE =
new PostgreSQLContainer("postgres:17-alpine");
static {
INSTANCE.start();
}
private SharedPostgres() {}
}
```
Test classes read `SharedPostgres.INSTANCE.getJdbcUrl()` and do **not** annotate it with `@Container` (that would stop it after the first class). An abstract base class with the static block works equally well.
Isolate data instead of containers: truncate tables in `@BeforeEach`, roll back transactions, or create a schema/database per class.
## Reuse between runs (local dev only)
Reuse keeps containers alive after the JVM exits so the next run is instant.
1. Opt in on the developer machine in `~/.testcontainers.properties`: `testcontainers.reuse.enable=true`.
2. Mark the container: `new PostgreSQLContainer("postgres:17-alpine").withReuse(true)`, and start it manually (static block or `start()`). Do not annotate it with `@Container`: the JUnit extension stops it after the tests, so nothing is reused.
Caveats: reused containers are never stopped by Testcontainers (clean manually with `docker rm -f`); state persists, so tests must clean their own data; reuse is ignored unless both settings are present, so it is safe to leave `withReuse(true)` in code. Do not enable it in CI.
## Parallel execution
- JUnit parallel mode with a shared container is fine if tests do not share rows; give each test its own tenant/schema/key prefix.
- Do not parallelize tests that truncate shared tables.
- Resource-hungry containers (Kafka, Elasticsearch) should stay singletons.
## Manual lifecycle
Containers are `AutoCloseable`:
```java
try (var redis = new GenericContainer<>("redis:7.4-alpine").withExposedPorts(6379)) {
redis.start();
// use redis.getHost(), redis.getMappedPort(6379)
}
```
## Ports and addresses
Never bind fixed host ports. Use `getHost()` and `getMappedPort(containerPort)`; for modules prefer the typed getters (`getJdbcUrl()`, `getBootstrapServers()`). Mapped ports are random per start.
License (MIT)
View full license text
MIT License Copyright GitHub, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.