Testcontainers runs external components in Docker containers directly from JUnit tests, giving Kafka Streams integration tests a live broker while managing the container lifecycle. section 14.1.5
A typical Kafka integration test uses Testcontainers to:
- Annotate the test class with @Testcontainers and a KafkaContainer field with @Container. section 14.1.5
- Use a static container to share one broker across test methods, or a nonstatic field to restart it for each test. section 14.1.5
- Read kafka.getBootstrapServers() when configuring Kafka Streams, producers, and consumers. section 14.1.5
- Delete test topics during teardown so repeated tests do not reuse stale data. section 14.1.5
Kafka Streams integration test
A test starts a Kafka broker, waits until KafkaStreams reaches RUNNING, produces timestamped records, reads the output topic, and compares the consumed records with expected hopping-window counts. The live broker accounts for startup time and stateful Kafka Streams behavior. section 14.1.5
Listing 14.22 Integration test with Testcontainers annotations
@Testcontainers #1
class StreamsCountHoppingWindowIntegrationTest {
@Container #2
private static final KafkaContainer kafka =
new KafkaContainer(
DockerImageName.parse("confluentinc/cp-kafka:7.5.1")); #3
The annotated KafkaContainer setup shows the minimal Testcontainers structure, including the Docker image and automatic lifecycle hooks. section 14.1.5




