Video in progress

Strong Middle 🧩 Microservices

How do you write an integration test with Testcontainers for a scenario that touches Kafka and PostgreSQL, and what does `@ServiceConnection` give you?

The test runs against real PostgreSQL and Kafka containers, so there are no differences like those you get with H2 or embedded Kafka. Since Boot 3.1, @ServiceConnection wires the container address into spring.datasource.* and spring.kafka.* automatically, so you don't have to write @DynamicPropertySource by hand.

📖 Answer

@SpringBootTest
@Testcontainers
class OrderFlowIT {

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

    @Container @ServiceConnection
    static KafkaContainer kafka = new KafkaContainer("apache/kafka:3.8.0"); // org.testcontainers.kafka

    @Autowired OrderService orders;
    @Autowired OutboxRelay relay;

    @Test
    void placedOrderReachesTopic() {
        orders.place(new PlaceOrder(42L, List.of(new Item("SKU-1", 2))));
        relay.publishPending();

        try (Consumer<String, String> consumer = testConsumer("orders")) {
            ConsumerRecord<String, String> r =
                KafkaTestUtils.getSingleRecord(consumer, "orders", Duration.ofSeconds(10));
            assertThat(r.value()).contains("\"type\":\"OrderPlaced\"");
        }
    }
}

Here testConsumer is a plain helper method that connects using kafka.getBootstrapServers(). @ServiceConnection recognizes the new org.testcontainers.kafka.KafkaContainer from Boot 3.4; older Boot uses org.testcontainers.containers.KafkaContainer (the Confluent image).

A few practical points:

  • Make the containers static, so there is one for all tests in the class. If you want a single container for the whole test suite, declare them as @Bean @ServiceConnection in a shared @TestConfiguration and have the tests import that configuration. The Spring test context is cached, so the containers aren't brought up again.
  • Don't wait for an async result with Thread.sleep. Use Awaitility: await().atMost(10, SECONDS).until(...).
  • Use the same image version as prod. With postgres:latest a test turns red one day for no apparent reason.
  • Each test should create its own data and not rely on leftovers from other tests. When you run them in parallel, that is the first thing that breaks.

Such tests are slower (a container start takes 5–15 seconds), so I write them for the main flows, not instead of unit tests: "order → outbox → Kafka", "a duplicate message isn't processed twice".