Video in progress
How do you test code that works with Kafka in an integration test?
There are two main ways: Spring's @EmbeddedKafka (a broker inside the JVM) and a real Kafka container with Testcontainers. Testcontainers is closer to prod; embedded starts faster and doesn't need Docker.
📖 Answer
With Testcontainers, @ServiceConnection shortens the setup in Spring Boot 3.1+ (the new org.testcontainers.kafka.KafkaContainer below needs Boot 3.4+ and Testcontainers 1.20+; the older org.testcontainers.containers.KafkaContainer works with the confluentinc/cp-kafka image):
@SpringBootTest
@Testcontainers
class OrderFlowIT {
@Container
@ServiceConnection
static KafkaContainer kafka =
new KafkaContainer(DockerImageName.parse("apache/kafka:3.8.0"));
@Autowired KafkaTemplate<String, OrderCreated> template;
@Autowired OrderRepository repo;
@Test
void orderIsSaved() {
template.send("orders", "o-1", new OrderCreated("o-1", 100));
await().atMost(Duration.ofSeconds(10))
.until(() -> repo.findById("o-1").isPresent());
}
}
To check an asynchronous result, use Awaitility instead of Thread.sleep: the tests get both faster and more stable.
Problems that come up in tests all the time:
- the consumer starts from
latestand the test message was sent before it: setauto-offset-reset: earliest; - tests share a topic and read each other's messages: use a unique topic or key per test;
- retry backoff stretches the test to minutes: shorten it in the test profile.
It's better to check the listener logic first with a plain unit test: no Kafka, just call the method directly.
Sign up to mark studied questions and save your progress.