Testcontainers with Spring Boot: PostgreSQL, Redis, and Kafka

Testcontainers with Spring Boot: PostgreSQL, Redis, and Kafka

Testcontainers spins up real Docker containers for your tests — no mocks, no H2 surprises, no "works on my machine" failures. This post covers practical setup for PostgreSQL, Redis, and Kafka with Spring Boot 3.x.

H2 in-memory databases are a trap. They let you write tests that pass locally and fail in production because H2 SQL dialect isn't PostgreSQL SQL dialect. @MockBean on your Redis client means you never find out your cache key logic is broken until users hit a bug. Testcontainers fixes this: real containers, real behavior, real confidence.

The tradeoff is speed — containers take a few seconds to start. The payoff is that your integration tests actually test integration.

Dependencies

Add Testcontainers to your pom.xml. Spring Boot 3.1+ has a BOM that manages versions:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.testcontainers</groupId>
      <artifactId>testcontainers-bom</artifactId>
      <version>1.19.7</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>junit-jupiter</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>postgresql</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>kafka</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>

For Redis, Testcontainers provides a generic container — there is no dedicated Redis module needed.

PostgreSQL Integration Tests

The simplest pattern uses @DynamicPropertySource to override Spring's datasource properties after the container starts:

@SpringBootTest
@Testcontainers
class OrderRepositoryIntegrationTest {

    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
            .withDatabaseName("testdb")
            .withUsername("testuser")
            .withPassword("testpass");

    @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);
    }

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private TestEntityManager entityManager;

    @Test
    void findByStatus_returnsMatchingOrders() {
        var order1 = new Order("prod-1", 2, OrderStatus.PENDING);
        var order2 = new Order("prod-2", 1, OrderStatus.SHIPPED);
        entityManager.persist(order1);
        entityManager.persist(order2);
        entityManager.flush();

        var pending = orderRepository.findByStatus(OrderStatus.PENDING);

        assertThat(pending).hasSize(1);
        assertThat(pending.get(0).getProductId()).isEqualTo("prod-1");
    }
}

The static keyword on both the container and @DynamicPropertySource is important. Static containers are started once per test class (not per test method), which keeps startup cost manageable. Spring Boot's @DynamicPropertySource is called before the application context starts, so the datasource is configured with the container's actual port.

Reusing Containers Across Test Classes

Starting a PostgreSQL container for every test class wastes time. The better pattern is a shared base class:

@SpringBootTest
@Testcontainers
abstract class DatabaseIntegrationTestBase {

    @Container
    static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine")
            .withDatabaseName("testdb")
            .withUsername("testuser")
            .withPassword("testpass")
            .withReuse(true);

    @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);
    }
}

With withReuse(true), Testcontainers keeps the container running between test class executions in the same JVM. You also need ~/.testcontainers.properties with testcontainers.reuse.enable=true on your machine.

Each test that modifies data should clean up after itself or run in a transaction that rolls back:

class OrderRepositoryTest extends DatabaseIntegrationTestBase {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @AfterEach
    void cleanup() {
        jdbcTemplate.execute("TRUNCATE TABLE orders CASCADE");
    }

    @Test
    void save_assignsId() {
        var order = orderRepository.save(new Order("prod-1", 2, OrderStatus.PENDING));
        assertThat(order.getId()).isNotNull();
    }
}

Redis with Testcontainers

Redis does not have a dedicated Testcontainers module, but GenericContainer works fine:

@SpringBootTest
@Testcontainers
class CacheServiceIntegrationTest {

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

    @DynamicPropertySource
    static void configureRedis(DynamicPropertyRegistry registry) {
        registry.add("spring.data.redis.host", redis::getHost);
        registry.add("spring.data.redis.port", () -> redis.getMappedPort(6379));
    }

    @Autowired
    private ProductCacheService cacheService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Test
    void cacheProduct_storesWithCorrectTtl() {
        var product = new Product("p-1", "Widget", BigDecimal.valueOf(9.99));

        cacheService.cacheProduct(product);

        var ttl = redisTemplate.getExpire("product:p-1");
        assertThat(ttl).isBetween(3500L, 3600L);
    }

    @Test
    void getProduct_returnsFromCacheOnSecondCall() {
        var product = new Product("p-2", "Gadget", BigDecimal.valueOf(19.99));
        cacheService.cacheProduct(product);

        var result1 = cacheService.getProduct("p-2");
        var result2 = cacheService.getProduct("p-2");

        assertThat(result1).isEqualTo(result2);
        assertThat(redisTemplate.keys("product:*")).hasSize(1);
    }
}

Kafka with Testcontainers

Kafka integration testing is where Testcontainers really shines. The alternative is either a local Kafka instance everyone has to run, or mocks that miss serialization bugs.

@SpringBootTest
@Testcontainers
class OrderEventPublisherIntegrationTest {

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

    @DynamicPropertySource
    static void configureKafka(DynamicPropertyRegistry registry) {
        registry.add("spring.kafka.bootstrap-servers", kafka::getBootstrapServers);
    }

    @Autowired
    private OrderEventPublisher publisher;

    @Test
    void publishOrderCreated_sendsToCorrectTopic() {
        var order = new Order("order-1", "prod-1", 2, OrderStatus.PENDING);
        var receivedEvents = new ArrayList<OrderEvent>();

        var consumer = buildTestConsumer();
        consumer.subscribe(List.of("orders.created"));

        publisher.publishOrderCreated(order);

        var deadline = System.currentTimeMillis() + 10_000;
        while (System.currentTimeMillis() < deadline && receivedEvents.isEmpty()) {
            var records = consumer.poll(Duration.ofMillis(500));
            records.forEach(r -> receivedEvents.add(r.value()));
        }
        consumer.close();

        assertThat(receivedEvents).hasSize(1);
        assertThat(receivedEvents.get(0).orderId()).isEqualTo("order-1");
        assertThat(receivedEvents.get(0).eventType()).isEqualTo("ORDER_CREATED");
    }

    private KafkaConsumer<String, OrderEvent> buildTestConsumer() {
        var props = new HashMap<String, Object>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers());
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-consumer-" + UUID.randomUUID());
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
        props.put(JsonDeserializer.TRUSTED_PACKAGES, "*");
        return new KafkaConsumer<>(props);
    }
}

Multi-Container Tests

Most real applications need multiple infrastructure services at once:

@SpringBootTest
@Testcontainers
abstract class FullStackIntegrationTestBase {

    static final Network NETWORK = Network.newNetwork();

    @Container
    static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine")
            .withNetwork(NETWORK)
            .withNetworkAliases("postgres")
            .withDatabaseName("testdb")
            .withUsername("testuser")
            .withPassword("testpass");

    @Container
    static final GenericContainer<?> REDIS = new GenericContainer<>("redis:7-alpine")
            .withNetwork(NETWORK)
            .withNetworkAliases("redis")
            .withExposedPorts(6379);

    @Container
    static final KafkaContainer KAFKA = new KafkaContainer(
            DockerImageName.parse("confluentinc/cp-kafka:7.6.0"))
            .withNetwork(NETWORK);

    @DynamicPropertySource
    static void configureAll(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", POSTGRES::getJdbcUrl);
        registry.add("spring.datasource.username", POSTGRES::getUsername);
        registry.add("spring.datasource.password", POSTGRES::getPassword);
        registry.add("spring.data.redis.host", REDIS::getHost);
        registry.add("spring.data.redis.port", () -> REDIS.getMappedPort(6379));
        registry.add("spring.kafka.bootstrap-servers", KAFKA::getBootstrapServers);
    }
}

The shared Network lets containers communicate with each other by alias — useful for services like Debezium that need to connect to Postgres by hostname.

Spring Boot 3.1+ ServiceConnection

Spring Boot 3.1 introduced @ServiceConnection, which eliminates the @DynamicPropertySource boilerplate for supported container types:

@SpringBootTest
@Testcontainers
class ModernIntegrationTest {

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

    @Container
    @ServiceConnection
    static RedisContainer redis = new RedisContainer("redis:7-alpine");

    // No @DynamicPropertySource needed — Spring Boot wires it automatically

    @Autowired
    private OrderRepository orderRepository;

    @Test
    void findAll_returnsEmpty_whenNoOrders() {
        assertThat(orderRepository.findAll()).isEmpty();
    }
}

@ServiceConnection works for PostgreSQL, MySQL, MariaDB, MongoDB, Redis, RabbitMQ, Kafka, and several others. For anything else, fall back to @DynamicPropertySource.

Waiting for Container Readiness

Testcontainers waits for containers to be ready by default, but the default strategy (TCP port check) does not always mean the service is actually accepting queries. Use waitingFor to be explicit:

@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
        .waitingFor(Wait.forSuccessfulCommand("pg_isready -U testuser -d testdb"))
        .withStartupTimeout(Duration.ofSeconds(60));

@Container
static GenericContainer<?> redis = new GenericContainer<>("redis:7-alpine")
        .withExposedPorts(6379)
        .waitingFor(Wait.forLogMessage(".*Ready to accept connections.*", 1));

This prevents flaky tests where the container is listening but the server is not yet ready to handle queries.

Test Performance Tips

  • Declare containers static — one container per test class, not one per test method
  • Use withReuse(true) across your CI runs (requires enabling in .testcontainers.properties)
  • Extend from a base class to share a single container across multiple test classes
  • Use @Transactional on test methods for rollback instead of truncating tables manually
  • Run integration tests in a separate Maven profile (-P integration-tests) so unit tests stay fast

Testcontainers adds maybe 5-10 seconds to a test run when containers are reused. That is a small price for eliminating the "works against H2 but fails in production" class of bugs.

Read more

Start now free