liveBook · Manning

@Testcontainers

As explained in Kafka Streams in Action, Second Edition

The @Testcontainers annotation is a Testcontainers JUnit Jupiter extension that manages container lifecycles declared in a test class.

@Testcontainers enables JUnit Jupiter to manage Testcontainers declared in a test class. It discovers fields annotated with @Container and controls their startup and shutdown. section 14.1.5

Configure the container field according to the desired test lifecycle:

  • Declare a static @Container field to share one KafkaContainer across all test methods; it starts before the first test and stops after the last. section 14.1.5
  • Declare a nonstatic @Container field to start and stop the container for each test; use this only when test isolation requires it. 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

A Kafka integration test combines @Testcontainers with a static @Container KafkaContainer configured from a Docker image name. section 14.1.5

How Kafka Streams in Action, Second Edition covers it

How deep it goes
Explains annotation discovery and static versus nonstatic lifecycles, but defers Docker fundamentals.
Examples
Uses a static KafkaContainer with confluentinc/cp-kafka:7.5.1 in a hopping-window integration test.
What it assumes
Assumes JUnit Jupiter, Testcontainers, Kafka, and Docker dependencies are configured.
What you can do after
Operate Kafka integration tests with automatically started and stopped containers.
How it connects
Connects JUnit Jupiter, @Container, KafkaContainer, Docker, and Kafka Streams integration testing.

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.