Kafka Containers
Testcontainers can be used to automatically instantiate and manage Apache Kafka containers. More precisely Testcontainers uses the official Docker images for Confluent OSS Platform
Benefits
- Running a single node Kafka installation with just one line of code
- No need to manage external Zookeeper installation, required by Kafka. But see below
Example
Create a KafkaContainer
to use it in your tests:
KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:6.2.1"))
The correspondence between Confluent Platform versions and Kafka versions can be seen in Confluent documentation
Now your tests or any other process running on your machine can get access to running Kafka broker by using the following bootstrap server location:
kafka.getBootstrapServers()
Options
Using external Zookeeper
If for some reason you want to use an externally running Zookeeper, then just pass its location during construction:
KafkaContainer kafka = new KafkaContainer(KAFKA_TEST_IMAGE)
.withNetwork(network)
.withExternalZookeeper("zookeeper:2181");
Multi-container usage
If your test needs to run some other Docker container which needs access to Kafka, do the following:
- Run your other container on the same network as Kafka container, e.g.:
GenericContainer<?> application = new GenericContainer<>(DockerImageName.parse("alpine"))
.withNetwork(network)
- Use
kafka.getNetworkAliases().get(0)+":9092"
as bootstrap server location. Or just give your Kafka container a network alias of your liking.
You will need to explicitly create a network and set it on the Kafka container as well as on your other containers that need to communicate with Kafka.
Adding this module to your project dependencies
Add the following dependency to your pom.xml
/build.gradle
file:
testImplementation "org.testcontainers:kafka:1.17.4"
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>kafka</artifactId>
<version>1.17.4</version>
<scope>test</scope>
</dependency>