testcontainers

v2026.09.24

Testcontainers for Docker-based integration testing in Java. Covers database containers, messaging systems, and Spring Boot @ServiceConnection. USE WHEN: user mentions "testcontainers", "docker test", "integration test", asks about "@ServiceConnection", "PostgreSQLContainer", "MongoDBContainer", "test database", "docker compose test" DO NOT USE FOR: Unit tests - use `junit`; REST API tests - use `rest-assured`; Tests without Docker - use H2 or embedded databases; Non-Java projects - check language-specific tools

GitHub
Install command
npx skhub add claude-dev-suite/testcontainers
Markdown
SKILL.md

Testcontainers - Quick Reference

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: testcontainers for comprehensive documentation.

When NOT to Use This Skill

  • Unit Tests - Use junit with Mockito for fast isolated tests
  • REST API Tests Only - Use rest-assured without containers if API is mocked
  • Environments Without Docker - Use H2 or embedded databases
  • CI with Limited Resources - Containers may be too heavy, use mocks
  • Non-Java Projects - Check language-specific Testcontainers libraries

Setup Base

Maven Dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-testcontainers</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>junit-jupiter</artifactId>
    <scope>test</scope>
</dependency>
<!-- Database specific -->
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>postgresql</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>mongodb</artifactId>
    <scope>test</scope>
</dependency>

Gradle Dependencies

testImplementation("org.springframework.boot:spring-boot-testcontainers")
testImplementation("org.testcontainers:junit-jupiter")
testImplementation("org.testcontainers:postgresql")
testImplementation("org.testcontainers:mongodb")

@ServiceConnection (Spring Boot 3.1+)

Pattern Raccomandato

@SpringBootTest
@Testcontainers
class MyIntegrationTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres =
        new PostgreSQLContainer<>("postgres:16-alpine");

    @Test
    void testWithDatabase() {
        // Connection auto-configured
    }
}

Container Supportati

ContainerMaven ArtifactConnection Details
PostgreSQLContainerpostgresqlJDBC + R2DBC
MySQLContainermysqlJDBC + R2DBC
MariaDBContainermariadbJDBC + R2DBC
MongoDBContainermongodbMongoConnectionDetails
KafkaContainerkafkaKafkaConnectionDetails
RedisContainer-RedisConnectionDetails
RabbitMQContainerrabbitmqRabbitConnectionDetails
ElasticsearchContainerelasticsearchElasticsearchConnectionDetails
CassandraContainercassandraCassandraConnectionDetails

GenericContainer con @ServiceConnection

@Container
@ServiceConnection(name = "redis")
static GenericContainer<?> redis =
    new GenericContainer<>("redis:7-alpine")
        .withExposedPorts(6379);

Lifecycle Management

Static Container (Shared across tests - RECOMMENDED)

@Testcontainers
class SharedContainerTest {

    @Container
    static PostgreSQLContainer<?> postgres =
        new PostgreSQLContainer<>("postgres:16-alpine");

    @Test
    void test1() { /* same container */ }

    @Test
    void test2() { /* same container */ }
}

Spring Bean Container (Best lifecycle control)

@TestConfiguration(proxyBeanMethods = false)
class TestContainersConfig {

    @Bean
    @ServiceConnection
    PostgreSQLContainer<?> postgresContainer() {
        return new PostgreSQLContainer<>("postgres:16-alpine");
    }
}

@SpringBootTest
@Import(TestContainersConfig.class)
class ManagedContainerTest {
    // Container lifecycle managed by Spring
    // Started before beans, stopped after beans
}

Container Reuse (Development)

static PostgreSQLContainer<?> postgres =
    new PostgreSQLContainer<>("postgres:16-alpine")
        .withReuse(true);

Richiede in ~/.testcontainers.properties:

testcontainers.reuse.enable=true

Database Containers

PostgreSQL

@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres =
    new PostgreSQLContainer<>("postgres:16-alpine")
        .withDatabaseName("testdb")
        .withUsername("test")
        .withPassword("test")
        .withInitScript("init.sql");

MongoDB

@Container
@ServiceConnection
static MongoDBContainer mongo =
    new MongoDBContainer("mongo:7.0")
        .withSharding();

MySQL

@Container
@ServiceConnection
static MySQLContainer<?> mysql =
    new MySQLContainer<>("mysql:8.0")
        .withDatabaseName("testdb")
        .withUsername("test")
        .withPassword("test");

Messaging Containers

Kafka

@Container
@ServiceConnection
static KafkaContainer kafka =
    new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:7.5.0"))
        .withKraft();

RabbitMQ

@Container
@ServiceConnection
static RabbitMQContainer rabbitmq =
    new RabbitMQContainer("rabbitmq:3.12-management")
        .withExposedPorts(5672, 15672);

Redis

@Container
@ServiceConnection
static GenericContainer<?> redis =
    new GenericContainer<>("redis:7-alpine")
        .withExposedPorts(6379);

Messaging Container Test Patterns

Dedicated skills: For comprehensive messaging test coverage, see messaging-testing-kafka, messaging-testing-rabbitmq, and messaging-testing.

Kafka: Produce → Consume → Assert

@SpringBootTest
@Testcontainers
class KafkaProduceConsumeTest {

    @Container
    @ServiceConnection
    static KafkaContainer kafka = new KafkaContainer(
        DockerImageName.parse("apache/kafka-native:3.8.0"));

    @Autowired
    private KafkaTemplate<String, OrderEvent> kafkaTemplate;

    @Autowired
    private OrderRepository orderRepository;

    @Test
    void shouldProcessOrderViaKafka() throws Exception {
        kafkaTemplate.send("orders", "key-1",
            new OrderEvent("123", "CREATED")).get(10, TimeUnit.SECONDS);

        await().atMost(Duration.ofSeconds(10))
            .untilAsserted(() ->
                assertThat(orderRepository.findById("123")).isPresent());
    }
}

RabbitMQ: Send → Listen → Assert

@SpringBootTest
@Testcontainers
class RabbitProduceConsumeTest {

    @Container
    @ServiceConnection
    static RabbitMQContainer rabbit = new RabbitMQContainer("rabbitmq:3.13-management");

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderRepository orderRepository;

    @Test
    void shouldProcessOrderViaRabbit() {
        rabbitTemplate.convertAndSend("orders.exchange", "orders.created",
            new OrderEvent("456", "CREATED"));

        await().atMost(Duration.ofSeconds(10))
            .untilAsserted(() ->
                assertThat(orderRepository.findById("456")).isPresent());
    }
}

Redis Pub/Sub: Publish → Subscribe → Assert

@SpringBootTest
@Testcontainers
class RedisPubSubTest {

    @Container
    @ServiceConnection(name = "redis")
    static GenericContainer<?> redis =
        new GenericContainer<>("redis:7-alpine").withExposedPorts(6379);

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Test
    void shouldPublishAndReceiveMessage() throws Exception {
        CountDownLatch latch = new CountDownLatch(1);
        List<String> received = new CopyOnWriteArrayList<>();

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisTemplate.getConnectionFactory());
        container.addMessageListener((message, pattern) -> {
            received.add(new String(message.getBody()));
            latch.countDown();
        }, new ChannelTopic("orders"));
        container.afterPropertiesSet();
        container.start();

        redisTemplate.convertAndSend("orders", "{\"orderId\":\"789\"}");

        assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
        assertThat(received.get(0)).contains("789");
        container.stop();
    }
}

Legacy Pattern (@DynamicPropertySource)

@Testcontainers
@SpringBootTest
class LegacyTest {

    @Container
    static PostgreSQLContainer<?> postgres =
        new PostgreSQLContainer<>("postgres:16");

    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }
}

Network & Compose

Container Network

@Testcontainers
class NetworkTest {

    static Network network = Network.newNetwork();

    @Container
    static PostgreSQLContainer<?> postgres =
        new PostgreSQLContainer<>("postgres:16")
            .withNetwork(network)
            .withNetworkAliases("postgres");

    @Container
    static GenericContainer<?> app =
        new GenericContainer<>("myapp:latest")
            .withNetwork(network)
            .dependsOn(postgres)
            .withEnv("DATABASE_HOST", "postgres");
}

Docker Compose

@Testcontainers
class ComposeTest {

    @Container
    static DockerComposeContainer<?> compose =
        new DockerComposeContainer<>(new File("docker-compose-test.yml"))
            .withExposedService("postgres", 5432)
            .withExposedService("redis", 6379);

    @Test
    void test() {
        String host = compose.getServiceHost("postgres", 5432);
        int port = compose.getServicePort("postgres", 5432);
    }
}

Wait Strategies

new GenericContainer<>("custom-image")
    .waitingFor(Wait.forHttp("/health").forStatusCode(200))
    .waitingFor(Wait.forLogMessage(".*Started.*", 1))
    .waitingFor(Wait.forListeningPort())
    .withStartupTimeout(Duration.ofMinutes(2));

Best Practices

DoDon't
Use static containersCreate container per test method
Use @ServiceConnectionManual property configuration
Use Spring Bean lifecycleJUnit lifecycle for app-dependent containers
Enable container reuse in devStart fresh containers every run
Use specific image tagsUse latest tag
Share containers via base classDuplicate container declarations

Common Issues

Container not starting

// Check Docker is running
// Check image exists
// Increase startup timeout
.withStartupTimeout(Duration.ofMinutes(5))

Port conflicts

// Always use exposed port mapping
container.getMappedPort(5432)
// Never hardcode ports

Slow tests

// Enable reuse
.withReuse(true)
// Use lighter images (-alpine)
new PostgreSQLContainer<>("postgres:16-alpine")

Anti-Patterns

Anti-PatternWhy It's BadSolution
Creating container per test methodExtremely slowUse static containers shared across tests
Not using @ServiceConnectionManual config duplicationLet Spring auto-configure from container
Using latest tagNon-deterministic testsPin specific version (postgres:16-alpine)
No withReuse for local devSlow dev feedback loopEnable reuse in ~/.testcontainers.properties
Hardcoded portsPort conflictsUse getMappedPort() for dynamic ports
Ignoring startup timeoutTests hangSet withStartupTimeout appropriately
Not cleaning up test dataTests interfere with each otherUse @Transactional or manual cleanup

Quick Troubleshooting

ProblemLikely CauseSolution
"Could not find image"Docker not running or image unavailableStart Docker, check image name
Container startup timeoutImage too large or slow startupIncrease timeout, use lighter images
Port already in usePrevious test didn't clean upUse dynamic ports with getMappedPort()
Tests very slowStarting containers every testUse static containers
Connection refusedUsing localhost instead of container hostUse container.getHost() and getMappedPort()
"@ServiceConnection not working"Wrong Spring Boot versionRequires Spring Boot 3.1+, check version

Reference Documentation

Discovery
Tags

No tags published for this skill.

Version
Latest version metadata

Version

v2026.09.24

Published

Sep 24, 2026

Category

Uncategorized

License

MIT

Source path

skills/testing/testcontainers

Default branch

main

Latest commit

9496306

Tree SHA

fe4e2f1