liveBook · Manning

Testcontainers

As explained in Kafka Streams in Action, Second Edition

Testcontainers is a library for running disposable containerized dependencies during automated tests and managing their lifecycle.

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

How Kafka Streams in Action, Second Edition covers it

How deep it goes
Explains annotations, container scope, broker configuration, startup waiting, production, consumption, assertions, and teardown.
Examples
Uses a KafkaContainer, timestamped records, hopping-window counts, output-topic consumption, and expected-record assertions.
What it assumes
Assumes Docker familiarity and introduces the Testcontainers annotations and Kafka-specific JUnit setup.
What you can do after
Operate/configure Kafka integration tests with managed containers, broker endpoints, lifecycle control, test data, and cleanup.
How it connects
Connects JUnit 5, Docker, Kafka brokers, Kafka Streams, producers, consumers, topics, and integration testing.

Also explained in

Compare how 5 books explain Testcontainers →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kafka Streams in Action, Second Edition. The section links point to the parts of the book it draws on.